Database Reference
In-Depth Information
i <- 1 # create a numeric variable
sport <- "football"
# create a character variable
flag <- TRUE
# create a logical variable
R provides several functions, such as class() and typeof() , to examine the
characteristics of a given variable. The class() function represents the abstract
class of an object. The typeof() function determines the way an object is stored
in memory. Although i appears to be an integer, i is internally stored using double
precision. To improve the readability of the code segments in this section, the
inline R comments are used to explain the code or to provide the returned values.
class(i) # returns "numeric"
typeof(i)
# returns "double"
class(sport)
# returns "character"
typeof(sport)
# returns "character"
class(flag)
# returns "logical"
typeof(flag)
# returns "logical"
Additional R functions exist that can test the variables and coerce a variable into a
specific type. The following R code illustrates how to test if i is an integer using the
is.integer() function and to coerce i into a new integer variable, j , using the
as.integer() function. Similar functions can be applied for double, character,
and logical types.
is.integer(i) # returns FALSE
j <- as.integer(i) # coerces contents of i into an
integer
is.integer(j)
# returns TRUE
The application of the length() function reveals that the created variables each
have a length of 1. One might have expected the returned length of sport to have
been 8 for each of the characters in the string "football" . However, these three
variables are actually one element, vectors .
length(i)
# returns 1
length(flag)
# returns 1
length(sport)
# returns 1 (not 8 for "football")
Search WWH ::




Custom Search