Skip to content
Tutorials Center
My learning

Topics

Lesson 7 of 39 ยท Data Types and Structures

Data Types and Coercion in R

Understand R's basic data types, how to check and convert them with class() and as.numeric(), how automatic coercion works, and how NA, NULL, NaN and Inf differ.

Every value in R has a type. The type decides what you can do with the value: you can add numbers, but not words; you can compare text alphabetically, but not average it. Many beginner bugs come from a value having a different type than expected, such as numbers read from a file as text. This lesson covers the basic types, how to inspect and convert them, and how R converts them for you without asking.

The atomic types

The simple building blocks are called atomic types. You will use these four all the time:

Type Example class()
Numeric (double) 3.14, 42 "numeric"
Integer 42L "integer"
Character (text) "hello" "character"
Logical TRUE, FALSE "logical"

Two more exist but are used less: complex numbers (2+3i) and raw bytes.

R
class(3.14)
#> [1] "numeric"

class(42L)
#> [1] "integer"

class("hello")
#> [1] "character"

class(TRUE)
#> [1] "logical"

By default, a number like 5 is stored as a double (a floating-point number), even though it looks whole. Add an L to get a true integer. typeof() reveals the storage type and is more precise than class():

R
typeof(5)
#> [1] "double"

typeof(5L)
#> [1] "integer"

For most work you never need to care about the difference. It becomes visible with very large counts (integers top out at 2,147,483,647) or when you need exact whole-number arithmetic.

Checking and converting

Each type has a test function starting with is. and a conversion function starting with as.:

R
is.numeric(5)
#> [1] TRUE

is.character(5)
#> [1] FALSE

as.numeric("42")
#> [1] 42

as.character(12.5)
#> [1] "12.5"

as.integer(3.9)      # truncates toward zero, does not round
#> [1] 3

as.logical("TRUE")
#> [1] TRUE

as.logical("yes")    # not recognized
#> [1] NA

When a conversion cannot work, R returns NA and prints a warning:

R
as.numeric("twelve")
#> [1] NA
#> Warning message:
#> NAs introduced by coercion

Logical values convert to numbers as TRUE = 1 and FALSE = 0. That makes counting easy:

R
passed <- c(TRUE, FALSE, TRUE, TRUE)
sum(passed)
#> [1] 3

mean(passed)     # share of TRUE values
#> [1] 0.75

Automatic (implicit) coercion

A vector can hold only one type, so when you mix types R converts everything to the most general one. The order is:

flowchart LR
    L["logical"] --> I["integer"] --> N["numeric"] --> C["character"]

Figure: coercion moves to the right. Logical becomes number, number becomes text.

R
c(TRUE, 2L)
#> [1] 1 2

c(1.5, TRUE)
#> [1] 1.5 1.0

c(1, "a")
#> [1] "1" "a"

The same thing happens inside operations:

R
TRUE + TRUE
#> [1] 2

"5" + 1
#> Error in "5" + 1 : non-numeric argument to binary operator

Arithmetic coerces logicals to numbers but refuses text. R is stricter here than the vector case, which is helpful.

Watch out when reading data. If a column that should be numeric contains a stray word such as "n/a", the whole column may be read as text. Then mean() fails or returns NA. Always check column types with str() after importing, as you will do in Reading and Writing Data.

Missing and special values

R has several values that mean "nothing" in different ways.

NA means a value is missing or unknown. It is not zero and not empty text, and it spreads through calculations because R cannot know the answer:

R
x <- c(4, NA, 10)

mean(x)
#> [1] NA

mean(x, na.rm = TRUE)    # remove NAs first
#> [1] 7

is.na(x)
#> [1] FALSE  TRUE FALSE

NA > 1
#> [1] NA

NA == NA          # unknown compared with unknown is unknown
#> [1] NA

That last line is why you must test with is.na(x), never x == NA. Logic has two exceptions where the answer is known anyway:

R
NA & FALSE
#> [1] FALSE

NA | TRUE
#> [1] TRUE

NaN means "not a number", the result of an undefined calculation such as 0 / 0. Inf and -Inf are infinities (1 / 0). Test them with is.nan() and is.infinite(). Note that is.na(NaN) is TRUE.

NULL means "no object at all". It has length zero and is what a function returns when it has nothing to return:

R
length(NULL)
#> [1] 0

class(NULL)
#> [1] "NULL"
Value Meaning Example source
NA Missing data Blank cell in a file
NaN Undefined math 0 / 0
Inf Overflow, division by zero 1 / 0
NULL No object, empty Empty result, removing a list item

Floating-point precision

Numbers are stored in binary, so some decimals cannot be represented exactly. This is true in every language, not just R:

R
0.1 + 0.2 == 0.3
#> [1] FALSE

isTRUE(all.equal(0.1 + 0.2, 0.3))
#> [1] TRUE

Never test decimals for exact equality. Use all.equal() (wrapped in isTRUE() when used in an if), which allows a tiny tolerance. Python behaves identically, as this runnable comparison shows:

Python Comparison: the same float issue in Python

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

R prints only seven significant digits by default, which is why 0.1 + 0.2 shows as 0.3 in R even though it is stored as slightly more. Use print(0.1 + 0.2, digits = 17) to see the real value.

Dates look like numbers but are not

Dates have their own class, Date, and are covered in Dates and Times. Factors, which store categories, get their own lesson next: Factors.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is typeof(5)?

    Plain numbers are doubles. You need 5L to get an integer.
  2. 2. What does c(TRUE, 2, "x") produce?

    Coercion goes logical, then numeric, then character, so everything becomes text.
  3. 3. Which test correctly detects a missing value in x?

    Comparing anything with NA gives NA. Use is.na().
  4. 4. What is sum(c(TRUE, FALSE, TRUE, TRUE))?

    TRUE counts as 1 and FALSE as 0, so three TRUE values sum to 3.
  5. 5. What does as.integer(3.9) return?

    as.integer() truncates toward zero. Use round() if you want rounding.

Summary

  • The atomic types are numeric (double), integer, character, logical, plus complex and raw.
  • Check with class(), typeof() and is.*(); convert with as.*().
  • Mixed vectors are coerced to the most general type: logical, then number, then text.
  • NA is missing, NaN is undefined math, Inf is infinity, NULL is nothing; test for missing values with is.na().
  • Do not compare decimals with ==; use all.equal().

Next: Factors