Testing and Coercing in R

Objects have a type, and you can test the type of an object using an is.type function (Table 2.4). For instance, mathematical functions expect numeric input and text-processing functions expect character input. Some types of objects can be coerced into other types. A familiar type of coercion occurs when we interpret the TRUE and FALSE of logical variables as numeric 1 and 0, respectively. Factor levels can be coerced to numbers. Numbers can be coerced into characters, but non-numeric characters cannot be coerced into numbers.

Table 2.4. Functions for testing (is) the attributes of different categories of object (arrays, lists, etc.) and for coercing (as) the attributes of an object into a specified form. Neither operation changes the attributes of the object.

images

as.numeric(factor(c("a","b","c")))

[1] 1 2 3

as.numeric(c("a","b","c"))

[1] NA NA NA
Warning message:
NAs introduced by coercion

as.numeric(c("a","4","c"))

[1] NA 4 NA
Warning message:
NAs introduced by coercion

If you try to coerce complex numbers to numeric the imaginary part will be discarded. Note that is.complex and is.numeric are never both TRUE.

We often want to coerce tables into the form of vectors as a simple way of stripping off their dimnames (using as.vector), and to turn matrixes into dataframes (as.data.frame). A lot of testing involves the NOT operator ! in functions to return an ...

Get The R Book now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.