SyntaxStudy
Sign Up
R R Data Types and Type Coercion
R Beginner 1 min read

R Data Types and Type Coercion

R has six atomic data types: double (numeric), integer, complex, character, logical, and raw. In everyday use you will encounter numeric, character, and logical most often. Integers are distinguished from doubles by appending an L suffix to a literal (e.g., 5L). Understanding types is important because many functions behave differently depending on the type of their input. Type coercion in R can be implicit or explicit. Implicit coercion happens automatically when mixing types in a vector: the less flexible type is converted to the more flexible one following the hierarchy logical < integer < double < complex < character. Explicit coercion is performed with the family of as.* functions such as as.numeric(), as.character(), and as.logical(). Special values are a key feature of R. NA represents a missing value and propagates through most computations. NULL represents the absence of an object entirely and has length zero. NaN (Not a Number) and Inf arise from numeric edge cases such as 0/0 and 1/0 respectively. The functions is.na(), is.null(), is.nan(), and is.infinite() let you test for these conditions before processing data.
Example
# Atomic types
dbl  <- 3.14          # numeric / double
int  <- 5L            # integer
cpx  <- 2 + 3i        # complex
chr  <- "hello"       # character
lgl  <- FALSE         # logical
raw_val <- as.raw(0x41) # raw (hex 0x41 = 65 = 'A')

cat(class(dbl), typeof(dbl), "\n")   # numeric  double
cat(class(int), typeof(int), "\n")   # integer  integer
cat(class(chr), typeof(chr), "\n")   # character character
cat(class(lgl), typeof(lgl), "\n")   # logical  logical

# Implicit coercion hierarchy: logical < integer < double < character
mixed <- c(TRUE, 2L, 3.5)      # all become double
cat(class(mixed), "\n")         # "numeric"

mixed2 <- c(1, "two", TRUE)    # all become character
cat(class(mixed2), "\n")        # "character"

# Explicit coercion
as.integer(3.9)     # 3  (truncates, does NOT round)
as.numeric("2.71")  # 2.71
as.logical(0)       # FALSE
as.logical(1)       # TRUE
as.character(99)    # "99"

# Special values
na_val  <- NA
null_val <- NULL
nan_val  <- NaN
inf_val  <- Inf

is.na(na_val)        # TRUE
is.null(null_val)    # TRUE
is.nan(nan_val)      # TRUE
is.infinite(inf_val) # TRUE

# NA propagates
5 + NA   # NA
mean(c(1, 2, NA))           # NA
mean(c(1, 2, NA), na.rm = TRUE)  # 1.5