R Data Types:
The Building Blocks
Master the four fundamental data types in R: numeric, integer, character, and logical: the foundation of every R program you will write.
What Are Data Types?
Every value you store in R has a data type: a label that tells R what kind of information it is and what operations are allowed on it. Think of data types as categories that determine how R treats your data.
The Four Core Types
Why Types Matter
R behaves differently depending on the type. Adding two numbers gives a sum, but adding two characters crashes. Knowing types prevents bugs and helps you write correct, efficient code.
mean() requires numeric input, not character.R's Type Hierarchy
The numeric Type
R's default number type is numeric (also called double). It stores decimal values using 64-bit floating-point representation. Even if you type 5, R stores it as 5.0 internally.
The integer Type
Integers are whole numbers explicitly created with the L suffix or by using as.integer(). They use less memory than numeric values and are important when interfacing with other systems.
The character Type
Character values store text strings. They are always wrapped in single or double quotes. Even a single letter like "a" is a character string in R: there is no separate "char" type.
The logical Type
Logical values are R's Boolean type: exactly TRUE or FALSE. They result from comparisons, and R treats them as 1 and 0 in numeric contexts.
numeric vs. integer
| numeric (double) | integer | |
|---|---|---|
| Created by | x <- 5 | x <- 5L |
| Stores | Decimal / floating point | Whole numbers only |
| Memory | 8 bytes per value | 4 bytes per value |
| Precision | ~15 significant digits | Exact (up to \( \pm (2^{31}-1) \)) |
is.numeric()? |
TRUE | TRUE |
is.integer()? |
FALSE | TRUE |
Check and Convert Types
Automatic Coercion in Vectors
R vectors can only hold one type. When you mix types with c(), R silently coerces everything to the most general type.
Example 1: Identifying Types
Example 2: Type Conversion
Example 3: Practical Application
Common Mistakes
is.integer() to check.Summary Table
| Type | Example | Check | Convert |
|---|---|---|---|
| numeric | 3.14, 42 | is.numeric() |
as.numeric() |
| integer | 5L, -2L | is.integer() |
as.integer() |
| character | "hello", "42" | is.character() |
as.character() |
| logical | TRUE, FALSE | is.logical() |
as.logical() |
Question 1 of 5
What is the output of class(42) in R?
Question 2 of 5
What does as.integer(4.8) return?
Question 3 of 5
What is the result of c(1, 2, "three")?
Question 4 of 5
What does sum(c(TRUE, FALSE, TRUE, TRUE)) return?
Question 5 of 5
Which function correctly tests whether x is a character string?
class(x) == "character"). as.character() converts, it does not test.