Data Types
Prerequisites: Variables and assignment
Every value in R has a type. The basic ones:
| Type | Example | Used for |
|---|---|---|
numeric |
42, 3.14 |
Numbers (stored as decimals) |
integer |
42L |
Whole numbers (the L suffix) |
character |
"hello" |
Text |
logical |
TRUE, FALSE |
Yes/no values |
Checking types
class(42)
class(42L)
class("42")
class(TRUE)
typeof(42)
is.numeric(42)
is.character(42)
[1] "numeric"
[1] "integer"
[1] "character"
[1] "logical"
[1] "double"
[1] TRUE
[1] FALSE
class()gives the kind of object, as most R functions see it.typeof()gives the low-level storage type: plain numbers are stored as"double"(double-precision decimals), even when they look whole.
Types matter because values that look alike behave differently:
"25" == 25
as.numeric("25") + 5
[1] TRUE
[1] 30
Surprise: "25" == 25 is TRUE, because R converts the number to text
before comparing. But "25" + 5 is an error. Convert text to a number
explicitly with as.numeric() before doing arithmetic.
Common mistakes
- Reading numbers from a file and getting text, because one cell
contained something like
"n/a". Check column types after importing data — you'll learn how in Level 2.