Skip to content
LumenaryAcademy
Foundations 55 min

Types, missing values and factors

R's atomic types and how it converts between them, the four kinds of nothing, factors for categorical data, dates, and the attributes that turn vectors into richer objects.

Code tested · 4AI-draftedAwaiting review by a computer scientist
MotivationH

What kind of data is this?

A column in a spreadsheet might hold amounts of money, counts of people, yes-or-no answers, names, categories such as "bus" or "bike", or dates. Each kind supports different operations: you can average amounts but not names, you can count categories but not meaningfully subtract them, and subtracting two dates should give a number of days. Before R can do the right thing with a value, it must know what kind of value it is.

This lesson covers how R represents these kinds of data. Most of it is short and precise, but the details matter more than they seem. A column of numbers read in as text will not add up. A category variable stored with its levels in alphabetical order will put "high" before "low" in every table and plot. A missing value handled carelessly will silently change a result. These are some of the most common bugs in real analyses, and every one of them is a question of types.

DefinitionsH

Atomic types and coercion

Definition— The atomic types

Every atomic vector has one of six types: logical (TRUE, FALSE), integer (42L), double (3.14, the default for numbers), character ("kiwi"), complex (2+3i) and raw (bytes). The first four cover almost all data analysis. typeof(x) reports the type; is.numeric(x) is true for both integers and doubles.

Because a vector has only one type, combining values of different types forces R to coerce them to a common one. It always moves "upwards" along a fixed order, choosing the type that can represent all the values without losing information: logical, then integer, then double, then character. TRUE becomes 1, numbers become their text form. You can also convert explicitly with the as.* family: as.numeric, as.integer, as.character, as.logical. When a conversion is impossible, the result is NA with a warning, not an error.

r
# The four atomic types you will meet every day.
values <- list(TRUE, 42L, 3.14, "kiwi")
for (v in values) cat(format(v), "is", typeof(v), "\n")

# c() must make all elements one type, so it coerces "upwards":
# logical -> integer -> double -> character.
c(TRUE, 2L)
c(TRUE, 2L, 3.5)
c(TRUE, 2L, 3.5, "four")

# Explicit conversion with as.*(); impossible conversions give NA (with a warning).
as.numeric("3.5")
as.integer(3.9)                       # truncates towards zero
as.logical(c("TRUE", "true", "T", "yes"))
suppressWarnings(as.numeric(c("12", "twelve", "1e3")))

# typeof() is the storage type; class() is what the object claims to be.
typeof(1:3); class(1:3)
typeof(Sys.Date()); class(Sys.Date())
text
TRUE is logical
42 is integer
3.14 is double
kiwi is character
[1] 1 2
[1] 1.0 2.0 3.5
[1] "TRUE" "2"    "3.5"  "four"
[1] 3.5
[1] 3
[1] TRUE TRUE TRUE   NA
[1]   12   NA 1000
[1] "integer"
[1] "integer"
[1] "double"
[1] "Date"

The first line used a list, which can hold elements of different types (the next lesson is about lists), so that each value kept its own type. Then each c() call shows coercion: one character string turned every element into text, including TRUE, which became "TRUE". as.integer(3.9) is 3, not 4: conversion truncates, so use round() first when you mean rounding. as.logical understands a few spellings of true and false but not "yes". And "twelve" could not become a number, so it became NA; the warning was silenced here with suppressWarnings, which in real code you should do only when you have checked that the NAs are expected.

The last two lines introduce a distinction you will use constantly. typeof() is how a value is stored; class() is what it is for the purposes of printing and of functions that behave differently for different kinds of object. Today's date (Sys.Date(), whose value varies but whose type does not) is stored as a double but has class "Date", which is why it prints as a date and why subtracting two dates gives a number of days.

DefinitionsH

Four kinds of nothing

R has four special values that are easy to confuse:

ValueMeaningTest
NAa value exists but is unknown ("not available")is.na(x)
NULLno object at all; a vector of length zerois.null(x)
NaNthe result of an undefined calculation, such as 0 / 0is.nan(x) (and is.na is also true)
Inf, -Infinfinitely large, such as 1 / 0is.infinite(x)
r
# Four kinds of "nothing", and how to test for them.
x <- c(1, NA, 3)          # NA: a value exists but is not known
y <- NULL                 # NULL: no object at all
z <- c(0 / 0, 1 / 0)      # NaN (not a number) and Inf

length(x); length(y)
is.na(x)
is.null(y)
is.nan(z); is.infinite(z)
is.na(NaN)                # NaN counts as missing too

# NA in logic: R's answer is NA only when the missing value could matter.
NA & FALSE                # FALSE whatever NA turns out to be
NA & TRUE                 # depends on NA
NA | TRUE
NA > 1
NA == NA                  # two unknowns are not known to be equal

# Every type has its own NA; c() keeps the type.
typeof(NA); typeof(NA_integer_); typeof(NA_character_)
typeof(c(1.5, NA))

# Counting missing values is the first step of any analysis.
sum(is.na(airquality$Ozone)); nrow(airquality)
text
[1] 3
[1] 0
[1] FALSE  TRUE FALSE
[1] TRUE
[1]  TRUE FALSE
[1] FALSE  TRUE
[1] TRUE
[1] FALSE
[1] NA
[1] TRUE
[1] NA
[1] NA
[1] "logical"
[1] "integer"
[1] "character"
[1] "double"
[1] 37
[1] 153

R's logic with NA follows the same reasoning as three-valued logic in SQL: if the answer would be the same whether the unknown value were TRUE or FALSE, R gives that answer; otherwise it gives NA. NA & FALSE is FALSE because "anything and false" is false; NA & TRUE depends on the unknown, so it is NA. Comparisons with NA, including NA == NA, are NA. That is why you must test for missing values with is.na(x), never with x == NA, which returns NA for every element.

The built-in airquality data set, daily air-quality measurements from New York in 1973, is missing 37 of its 153 ozone readings, which is typical of real data. Counting missing values, per column, before computing anything is one of the habits that separates careful analysts from the rest; colSums(is.na(df)) does it for a whole table at once.

Worked examplesH

Factors: categorical data

Definition— Factor

A factor represents a categorical variable: a vector whose values come from a fixed set of categories called levels. Internally it is an integer vector of codes, each pointing into the levels, with class "factor". An ordered factor additionally records that the levels have a natural order, such as small, medium and large.

Factors matter because statistics treats categories specially. A model formula that includes a factor fits a separate effect for each level, a table counts each level including those that never occur, and plots draw categories in level order. Getting the levels right is therefore part of getting the analysis right.

r
# A factor stores categories as integer codes plus a set of levels.
transport <- c("bus", "walk", "bike", "bus", "car", "walk", "bus")
f <- factor(transport)
f
levels(f)
as.integer(f)              # the codes, pointing into levels(f)
table(f)

# Levels default to alphabetical order; set them to match the meaning.
f2 <- factor(transport, levels = c("walk", "bike", "bus", "car", "train"))
table(f2)                  # an empty level is still counted, as 0
table(droplevels(f2))

# Ordered factors know that their levels have an order.
size <- factor(c("M", "S", "L", "M", "XL"),
               levels = c("S", "M", "L", "XL"), ordered = TRUE)
size
size >= "L"
max(size)

# The classic trap: numbers stored as a factor.
codes <- factor(c("10", "5", "20"))
as.numeric(codes)                  # the level codes, not the numbers!
as.numeric(as.character(codes))    # convert to text first
text
[1] bus  walk bike bus  car  walk bus
Levels: bike bus car walk
[1] "bike" "bus"  "car"  "walk"
[1] 2 4 1 2 3 4 2
f
bike  bus  car walk
   1    3    1    2
f2
 walk  bike   bus   car train
    2     1     3     1     0

walk bike  bus  car
   2    1    3    1
[1] M  S  L  M  XL
Levels: S < M < L < XL
[1] FALSE FALSE  TRUE FALSE  TRUE
[1] XL
Levels: S < M < L < XL
[1] 1 3 2
[1] 10  5 20

By default factor() sorts the levels alphabetically, which is rarely the order that means something. Giving levels = explicitly put the modes of transport in order of distance and added a level, train, that nobody chose; table() reports it as 0, which is exactly what a survey report should do. droplevels() removes unused levels when you do not want them. The ordered factor printed its levels with < signs and allowed comparisons and max(), which an unordered factor would refuse.

The last three lines are a trap that has caught nearly every R user once. A factor whose labels look like numbers is still a factor, and as.numeric() returns its integer codes (the levels "10", "20", "5" sort as text, so "10" is level 1). Convert to character first, then to numeric.

Note

Until R 4.0 (2020), data.frame() and read.csv() converted every text column into a factor by default (stringsAsFactors = TRUE), which caused that trap constantly. Since 4.0, text stays text unless you ask for factors. You will still see stringsAsFactors = FALSE in older code and answers online; it is now the default.

ComputationC

Dates, attributes and matrices

Dates in R are stored as the number of days since 1 January 1970, with class "Date". as.Date("2026-03-14") parses the international ISO 8601 format; other formats need a format argument such as "%d/%m/%Y". Arithmetic works in days, diff() and subtraction give time differences, and format() turns dates back into text in any layout. For times of day there is POSIXct, seconds since 1970 with a time zone, which the lubridate package from the tidyverse makes friendlier.

r
# Dates are numbers of days since 1970-01-01, with class "Date".
d <- as.Date(c("2026-03-14", "2026-07-01", "2026-12-25"))
d
as.numeric(d[1])
diff(d)                                   # differences between neighbours
d[3] - d[1]
format(d, "%d %B %Y")                     # month names follow the locale
weekdays(d)
seq(as.Date("2026-01-31"), by = "month", length.out = 3)

# Attributes: extra information attached to a vector.
# A matrix is a vector with a "dim" attribute.
m <- matrix(1:6, nrow = 2)
m
attributes(m)
dim(m); t(m)
m * 10                                    # still vectorised
text
[1] "2026-03-14" "2026-07-01" "2026-12-25"
[1] 20526
Time differences in days
[1] 109 177
Time difference of 286 days
[1] "14 March 2026"    "01 July 2026"     "25 December 2026"
[1] "Saturday"  "Wednesday" "Friday"
[1] "2026-01-31" "2026-03-03" "2026-03-31"
     [,1] [,2] [,3]
[1,]    1    3    5
[2,]    2    4    6
$dim
[1] 2 3

[1] 2 3
     [,1] [,2]
[1,]    1    2
[2,]    3    4
[3,]    5    6
     [,1] [,2] [,3]
[1,]   10   30   50
[2,]   20   40   60

Look at the monthly sequence starting on 31 January: the next "month" is 3 March, because 31 February does not exist and R rolls over into March. Month arithmetic on the 29th, 30th or 31st needs care in every language; in R, starting from the first of the month and subtracting a day is a common workaround. Month and weekday names come from your computer's language settings, so the same code prints them in Spanish or Swahili elsewhere.

Dates illustrate a general mechanism. Any vector can carry attributes, named pieces of extra information. names is one; class is another, and it changes how generic functions such as print, format and summary treat the vector; dim is a third. Give a vector of six numbers a dim of c(2, 3) and it becomes a matrix with 2 rows and 3 columns, filled column by column. A matrix is still an atomic vector underneath, so arithmetic remains element by element, and t() transposes it. Matrices are central to statistics (regression is matrix algebra), but in day-to-day analysis you will spend more time with data frames, which can hold columns of different types.

Common misconceptionsH

Type mistakes that look like data problems

Misconception

"The column must contain a typo, because mean() says the argument is not numeric." Usually one value, such as "n/a" or "12,5" with a decimal comma, made the whole column character when it was read. Find the culprits with x[is.na(suppressWarnings(as.numeric(x)))], fix the reading (for example read.csv(..., na.strings = "n/a"), or dec = ","), and convert.

Misconception

"NULL and NA both mean missing." NA is a placeholder inside a vector, keeping its position: c(1, NA, 3) has length 3. NULL is the absence of an object; c(1, NULL, 3) has length 2. A function that "returns nothing" returns NULL; a survey answer that was not given is NA.

Misconception

"Factors and character vectors are interchangeable." They print alike, but a factor has a fixed set of levels: assigning a value that is not a level produces NA with a warning, and comparing two factors with different levels is an error. Keep text as character while cleaning it, and make it a factor, with deliberate levels, when you are ready to analyse or plot.

Misconception

"Integers are the safe choice for whole numbers." R's integers are 32-bit, so they stop at 2,147,483,647 (.Machine$integer.max); adding 1L to that gives NA with a warning about integer overflow. Doubles represent every whole number exactly up to about 9 × 10¹⁵, which is why R makes numbers doubles by default. Use integers when a function asks for them or memory is tight, not for safety.

ExplanationH

Checking types in practice

Experienced analysts treat types as something to verify, not assume, at the boundary where data enters R. A few habits make that cheap:

  • Look before you compute. str(df) lists every column with its type and first values; summary(df) adds ranges and counts of NAs. A column of ages listed as chr instead of num tells you at once that something in the file is not a number.
  • Say what you expect. stopifnot(is.numeric(df$age), all(df$age >= 0, na.rm = TRUE)) at the top of a script turns a silent misunderstanding into an immediate, clear error. Packages such as validate and pointblank grow this idea into full data-validation reports.
  • Read with explicit types. Base R's read.csv() guesses each column's type; colClasses = c(id = "character", score = "numeric") tells it instead, which also keeps identifiers such as postcodes or phone numbers with leading zeros from being read as numbers and losing them. The tidyverse's readr::read_csv() reports the types it guessed and has a col_types argument for the same purpose.
  • Make factors last. Clean and recode text while it is character, then convert to a factor with the levels in a meaningful order, just before modelling, tabulating or plotting.

Why does R have factors at all, when most languages manage with strings? They come from S's statistical modelling software of the early 1990s, where categorical variables needed a fixed set of levels to build model matrices, and where storing a small integer per row instead of a repeated string saved scarce memory. The memory argument has faded (R now stores each distinct string only once anyway), but the modelling argument has not: the levels of a factor are the categories a model estimates effects for, and their order decides which level is the baseline. You will see this in the lesson on statistical models.

Exercises

Exercises

1. Types, missing values and factors

Warm-upComputational

What does typeof(c(1L, TRUE, NA)) print?

2. Types, missing values and factors

CoreComputational

What does c(1, "2", TRUE) print? Write it with single spaces.

3. Types, missing values and factors

StretchComputational

What does this print?

f <- factor(c("30", "5", "100"))
sum(as.numeric(f))

4. Types, missing values and factors

CoreComputational

What is length(c(1, NULL, NA, 3))?

5. Types, missing values and factors

CoreHuman

Which of these expressions evaluate to TRUE? List their letters.

  • A: NA | TRUE
  • B: NA & FALSE
  • C: is.na(NaN)
  • D: NA > NA
  • E: is.null(NA)
  • F: is.na(c(1, NA))[2]

Write elements separated by commas. Order and repeats don’t matter — just like in a set!

6. Types, missing values and factors

Warm-upComputational

How many days does as.Date("2026-03-01") - as.Date("2026-02-01") report?

7. Types, missing values and factors

CoreHuman

A survey column holds the answers "low", "medium" and "high". Which line creates a factor that tables and plots will show in the natural order and that supports comparisons like x > "low"?

Choose one

Further reading and resources