Yanshuai Cao
Yanshuai Cao

Reputation: 1297

How to get the container type of an object in R?

Suppose I have an object called v, how do I find out its container type (a vector, a list, a matrix, etc.), without trying each of the is.vector(v), is.list(v) ... ?

Upvotes: 6

Views: 2352

Answers (1)

sebastian-c
sebastian-c

Reputation: 15395

There are three functions which will be helpful for you: mode, str and class

First, let's make some data:

nlist <- list(a=c(1,2,3), b=c("a", "b", "c"), c=matrix(rnorm(10),5))
ndata.frame <- data.frame(a=c("a", "b", "c"), b=1:3)
ncharvec <- c("a", "b", "c")
nnumvec <- c(1, 2, 3)
nintvec <- 1:3

So let's use the functions I mentioned above:

mode(nlist)
[1] "list"

str(nlist)
List of 3
 $ a: num [1:3] 1 2 3
 $ b: chr [1:3] "a" "b" "c"
 $ c: num [1:5, 1:2] -0.9469 -0.0602 -0.3601 0.9594 -0.4348 ...

class(nlist)
[1] "list"

Now for the data frame:

mode(ndata.frame)
[1] "list"

This may surprise, you but data frames are simply a list with a data.frame class attribute.

str(ndata.frame)
'data.frame':   3 obs. of  2 variables:
 $ a: Factor w/ 3 levels "a","b","c": 1 2 3
 $ b: int  1 2 3
class(ndata.frame)
[1] "data.frame"

Note that there are different modes of vectors:

mode(ncharlist)
[1] "character"
mode(nnumvec)
[1] "numeric"
mode(nintvec)
[1] "numeric"

Also see that although nnumvec and nintvec appear identical, they are quite different:

str(nnumvec)
 num [1:3] 1 2 3
str(nintvec)
 int [1:3] 1 2 3

class(nnumvec)
[1] "numeric"
class(nintvec)
[1] "integer"

Depending on which of these you want should determine what function you use. str is a generally good function to look at variables whereas the other two are more useful in functions.

Upvotes: 9

Related Questions