Selecting Variables on the Basis of their Attributes
In this example, we want to extract all of the columns from nums (above) that are numeric. Use sapply to obtain a vector of logical values:
sapply(nums,is.numeric) name date response treatment dates FALSE FALSE TRUE FALSE TRUE
Now use this object to form the column subscripts to extract the two numeric variables:
nums[,sapply(nums,is.numeric)]
response dates
1 0.05963704 2003-08-25
2 1.46555993 2003-05-21
3 1.59406539 2003-10-12
4 2.09505949 2003-12-02
Note that dates is numeric but date was not (it is a factor, having been converted from a character string by the read.table function).
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.