R Tutorial menu

R Data Types and Operators

Every value in R has a type, and operators let you calculate and compare values.

The Basic Data Types

TypeExampleMeaning
numeric12.5, 40Numbers with or without decimals
integer40LWhole numbers (the L makes it an integer)
character"Ali"Text
logicalTRUE, FALSETrue or false
complex3 + 2iComplex numbers

Checking the Type

Use class():

Example

r
class(12.5)
class(40)
class(40L)
class("Karachi")
class(TRUE)
Output
[1] "numeric"
[1] "numeric"
[1] "integer"
[1] "character"
[1] "logical"

In R, a number like 40 is numeric (a decimal type) by default. Add L only when you really need an integer.

Write TRUE and FALSE in capital letters. R also accepts T and F, but they can be overwritten by accident, so the full words are safer.

Converting Between Types

Use the as. functions:

Example

r
as.numeric("250")
as.integer(9.8)
as.character(100)
as.logical("TRUE")
as.numeric("hello")
Output
[1] 250
[1] 9
[1] "100"
[1] TRUE
[1] NA
Warning message:
NAs introduced by coercion 

NA means "not available", R's way of saying a value is missing. Text that is not a number cannot be converted, so R gives NA and a warning.

Arithmetic Operators

OperatorMeaningExampleResult
+ - * /Basic maths7 / 23.5
^Power2^532
%%Remainder17 %% 52
%/%Whole-number division17 %/% 53

Example

r
price <- 350
qty <- 4
total <- price * qty
total
total %/% 1000
round(1234.567, 1)
sqrt(144)
Output
[1] 1400
[1] 1
[1] 1234.6
[1] 12

Comparison Operators

== (equal), != (not equal), >, <, >= and <= give TRUE or FALSE:

Example

r
marks <- 72
marks >= 50
marks == 100
"ali" == "Ali"
Output
[1] TRUE
[1] FALSE
[1] FALSE

Logical Operators

OperatorMeaning
&AND: both must be TRUE
the pipe signOR: at least one must be TRUE
!NOT: flips TRUE and FALSE

Example

r
age <- 20
has_id <- TRUE
age >= 18 & has_id
!has_id
age < 18 || has_id
Output
[1] TRUE
[1] FALSE
[1] TRUE

The double forms && and || (two pipe signs) check only single values and are used inside if conditions.

Text Functions

Example

r
course <- "Data Analysis"
nchar(course)
toupper(course)
substr(course, 1, 4)
grepl("Data", course)
Output
[1] 13
[1] "DATA ANALYSIS"
[1] "Data"
[1] TRUE

Exercise

Exercise

What does class(25L) return in R?

Learn R with a teacher

Join the Python Programming course at Workownix, online or in Orangi Town, Karachi, and get a certificate.

See the course Ask on WhatsApp