R Data Types and Operators
Every value in R has a type, and operators let you calculate and compare values.
The Basic Data Types
| Type | Example | Meaning |
|---|---|---|
numeric | 12.5, 40 | Numbers with or without decimals |
integer | 40L | Whole numbers (the L makes it an integer) |
character | "Ali" | Text |
logical | TRUE, FALSE | True or false |
complex | 3 + 2i | Complex numbers |
Checking the Type
Use class():
Example
class(12.5)
class(40)
class(40L)
class("Karachi")
class(TRUE)[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
as.numeric("250")
as.integer(9.8)
as.character(100)
as.logical("TRUE")
as.numeric("hello")[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
| Operator | Meaning | Example | Result |
|---|---|---|---|
+ - * / | Basic maths | 7 / 2 | 3.5 |
^ | Power | 2^5 | 32 |
%% | Remainder | 17 %% 5 | 2 |
%/% | Whole-number division | 17 %/% 5 | 3 |
Example
price <- 350
qty <- 4
total <- price * qty
total
total %/% 1000
round(1234.567, 1)
sqrt(144)[1] 1400 [1] 1 [1] 1234.6 [1] 12
Comparison Operators
== (equal), != (not equal), >, <, >= and <= give TRUE or FALSE:
Example
marks <- 72
marks >= 50
marks == 100
"ali" == "Ali"[1] TRUE [1] FALSE [1] FALSE
Logical Operators
| Operator | Meaning |
|---|---|
& | AND: both must be TRUE |
| the pipe sign | OR: at least one must be TRUE |
! | NOT: flips TRUE and FALSE |
Example
age <- 20
has_id <- TRUE
age >= 18 & has_id
!has_id
age < 18 || has_id[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
course <- "Data Analysis"
nchar(course)
toupper(course)
substr(course, 1, 4)
grepl("Data", course)[1] 13 [1] "DATA ANALYSIS" [1] "Data" [1] TRUE
Exercise
Exercise
What does class(25L) return in R?
