R Data Types
R sorts every value you create into one of a handful of basic data types, and knowing them well saves you from confusing bugs later.
The Building Blocks: R's Basic Types
Every value in R belongs to one of a small set of basic types, often called atomic types. Knowing which type a value has lets you predict how R will treat it in calculations, comparisons, and function calls, and it explains a surprising number of "why isn't this working" moments.
- numeric - any decimal number, e.g. 4.5
- integer - whole numbers marked with an L, e.g. 12L
- character - text wrapped in quotes, e.g. "hello"
- logical - TRUE or FALSE
- complex - a number with an imaginary part, e.g. 2+3i
Example
age <- 29L
price <- 19.99
name <- "Nimbus"
is_member <- TRUE
mystery <- 2 + 3i
class(age)
class(price)
class(name)
class(is_member)
class(mystery)Checking and Converting Types
class() tells you the type R has stored a value as, while as.numeric(), as.character(), and similar as.xxx() functions convert a value from one type to another. Conversion only succeeds if the value makes sense in the new type - turning "87.5" into a number works fine, but turning "hello" into a number produces NA with a warning.
Checking and Converting
score <- "87.5"
class(score) # "character"
is.numeric(score) # FALSE
score <- as.numeric(score)
class(score) # "numeric"
score + 12.5 # 100Special Values Worth Knowing
- NA - a value that is missing or unknown
- NULL - the complete absence of a value, not even a placeholder
- NaN - the result of an undefined calculation such as 0/0
- Inf and -Inf - what you get from dividing a nonzero number by zero
Once you can spot these types on sight, reading error messages and debugging unexpected results gets much easier - most type-related bugs come down to a value being stored in a different type than you assumed.
Exercise: R Data Types
Which built-in function reports the data type/class of an R object?