TExcelTAD
Home › R › R Data Types

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"
r · try it yourself
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:

r · try it yourself
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:

r · try it yourself
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:

r · try it yourself
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
r · try it yourself
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)?

  1. "integer"
  2. "numeric"
  3. "double"
  4. "number"

What is the type of c(1, "a", TRUE)?

  1. list
  2. numeric
  3. character
  4. logical

What does as.integer(4.8) return?

  1. 5
  2. 4
  3. 4.8
  4. NA