R Language Classes Vectors and lists

Example

Data in R are stored in vectors. A typical vector is a sequence of values all having the same storage mode (e.g., characters vectors, numeric vectors). See ?atomic for details on the atomic implicit classes and their corresponding storage modes: "logical", "integer", "numeric" (synonym "double"), "complex", "character" and "raw". Many classes are simply an atomic vector with a class attribute on top:

x <- 1826
class(x) <- "Date"
x
#  "1975-01-01"
x <- as.Date("1970-01-01")
class(x)
# "Date"
is(x,"Date")
# TRUE
is(x,"integer")
# FALSE
is(x,"numeric")
# FALSE
mode(x)
# "numeric"

Lists are a special type of vector where each element can be anything, even another list, hence the R term for lists: "recursive vectors":

mylist <- list( A = c(5,6,7,8), B = letters[1:10], CC = list( 5, "Z") )

Lists have two very important uses:

• Since functions can only return a single value, it is common to return complicated results in a list:

f <- function(x) list(xplus = x + 10, xsq = x^2)

f(7)
# \$xplus
#  17
#
# \$xsq
#  49

• Lists are also the underlying fundamental class for data frames. Under the hood, a data frame is a list of vectors all having the same length:

L <- list(x = 1:2, y = c("A","B"))
DF <- data.frame(L)
DF
#   x y
# 1 1 A
# 2 2 B
is.list(DF)
#  TRUE

The other class of recursive vectors is R expressions, which are "language"- objects PDF - Download R Language for free