typeof(TRUE)
[1] "logical"
Lecture 8
An object’s type indicates how it is stored in memory.
You’ll commonly encounter:
logical
integer
double
character
You’ll less commonly encounter:
list
NULL
complex
raw
Can you use different types of data together? Sometimes… but be careful!
"3" + 3
Error in "3" + 3: non-numeric argument to binary operator
Vectors are constructed using the c
function
without intention…
c(2, "Just this one!")
[1] "2" "Just this one!"
R will happily convert between various types without complaint when different types of data are concatenated in a vector. This is NOT always a good thing.
without intention…
c(FALSE, 3L)
[1] 0 3
c(1.2, 3L)
[1] 1.2 3.0
c(2L, "two")
[1] "2" "two"
with intention…
with intention…
Explicit coercion:
When you call a function like:
Implicit coercion:
Happens when you use a vector in a specific context that expects a certain type of vector.
We can think of data frames like like vectors of equal length glued together
df <- data.frame(x = 1:2, y = 3:4)
df
x y
1 1 3
2 2 4
We can think of data frames like like vectors of equal length glued together
df <- data.frame(x = 1:2, y = 3:4)
df
x y
1 1 3
2 2 4
pull()
function, we extract a vector from the data framedf |>
pull(y)
[1] 3 4
today <- as.Date("2025-05-27")
today
[1] "2025-05-27"
typeof(today)
[1] "double"
class(today)
[1] "Date"
We can think of dates like an integer (the number of days since the origin, 1 Jan 1970) and an integer (the origin) glued together
as.integer(today)
[1] 20235
as.integer(today) / 365 # roughly 55 yrs
[1] 55.43836
R uses factors to handle categorical variables with a fixed and known set of possible values
[1] June July June August June
Levels: August July June
We can think of factors like character (level labels) and an integer (level numbers) glued together
glimpse(months_factor)
Factor w/ 3 levels "August","July",..: 3 2 3 1 3
as.integer(months_factor)
[1] 3 2 3 1 3
We can use the forcats package (in tidyverse) to work with factors!
Some commonly used functions are:
fct_relevel(): reorder factors by hand
fct_reorder(): reorder factors by another variable
fct_infreq(): reorder factors by frequency
fct_rev(): reorder factors by reversing
amounts <- c("low", "medium", "high", "high", "medium")
amounts_factor <- factor(amounts)
amounts_factor
[1] low medium high high medium
Levels: high low medium
fct_relevel(amounts_factor, c("low", "medium", "high"))
[1] low medium high high medium
Levels: low medium high