R Data Types
Every value in R has a type. R works out the type from the value itself, so you never declare it, but knowing the types explains a lot of R's behaviour.
The basic (atomic) types
| Type | Examples | class() |
|---|---|---|
| numeric (double) | 3.14, 42, -1e6 |
"numeric" |
| integer | 42L, 1:10 |
"integer" |
| character | "hello", 'R' |
"character" |
| logical | TRUE, FALSE, NA |
"logical" |
| complex | 2+3i |
"complex" |
| raw | as.raw(255) |
"raw" |
price <- 19.99
count <- 3L
label <- "widget"
in_stock <- TRUE
z <- 1+2i
class(price)
class(count)
class(label)
class(in_stock)
class(z)[1] "numeric"
[1] "integer"
[1] "character"
[1] "logical"
[1] "complex"
Note that a plain whole number such as 42 is numeric (a double), not an integer. Add the L suffix to get a true integer.
class(), typeof() and is.*()
class() describes what an object is for the purpose of printing and methods; typeof() shows how R stores it internally. The is.*() functions answer yes/no questions:
typeof(42)
typeof(42L)
typeof(mean)
is.numeric(42L)
is.character("42")
is.logical(NA)[1] "double"
[1] "integer"
[1] "closure"
[1] TRUE
[1] TRUE
[1] TRUE
is.numeric() is TRUE for both doubles and integers, because both are numbers.
Everything is a vector
There are no scalar types in R. A single value is just a vector of length 1, and a vector holds values of one type:
length(5)
nums <- c(1, 2, 3)
class(nums)
mixed <- c(1, "two", TRUE)
mixed
class(mixed)[1] 1
[1] "numeric"
[1] "1" "two" "TRUE"
[1] "character"
When you combine different types with c(), R coerces them to the most flexible type: logical → integer → numeric → character. That is why 1 and TRUE became strings above. Use a list (covered later) when you really need mixed types.
Converting between types
The as.*() functions convert explicitly. If a conversion isn't possible, you get NA and a warning:
as.numeric("3.5")
as.integer(7.9)
as.character(100)
as.logical(c("TRUE", "yes", "F"))
as.numeric(TRUE)
as.numeric("abc")[1] 3.5
[1] 7
[1] "100"
[1] TRUE NA FALSE
[1] 1
[1] NA
Warning message:
NAs introduced by coercion
Notice that as.integer() truncates instead of rounding, and that only a few spellings ("TRUE", "true", "T", "FALSE", …) convert to logicals.
Special values
| Value | Meaning |
|---|---|
NA |
missing value ("not available") |
NULL |
the absence of an object (length 0) |
NaN |
"not a number", e.g. 0 / 0 |
Inf, -Inf |
infinity, e.g. 1 / 0 |
c(1, NA, 3)
length(NULL)
0 / 0
1 / 0
is.na(NA)[1] 1 NA 3
[1] 0
[1] NaN
[1] Inf
[1] TRUE
Test yourself
What is class(10)?
- "integer"
- "numeric"
- "double"
- "number"
What is the type of c(1, "a", TRUE)?
- list
- numeric
- character
- logical
What does as.integer(4.8) return?
- 5
- 4
- 4.8
- NA