Jeroen Ooms
Jeroen Ooms

Reputation: 32978

How to test if object is a vector

How to test if an object is a vector, i.e. mode logical, numeric, complex or character? The problem with is.vector is that it also returns TRUE for lists and perhaps other types:

> is.vector(list())
[1] TRUE

I want to know if it is a vector of primitive types. Is there a native method for this, or do I have to go by storage mode?

Upvotes: 33

Views: 49718

Answers (4)

scottkosty
scottkosty

Reputation: 2570

To check that an object obj is a vector, but not a list or matrix, consider:

is.vector(obj) && is.atomic(obj)

Using only is.vector(obj) returns TRUE for lists but not for matrices; and is.atomic(obj) returns TRUE for matrices but not for lists. Here are some sample checks:

mymatrix <- matrix()
mylist <- list()
myvec <- c("a", "b", "c")
is.vector(mymatrix) && is.atomic(mymatrix) # FALSE
is.vector(mylist) && is.atomic(mylist) # FALSE
is.vector(myvec) && is.atomic(myvec) # TRUE

Upvotes: 4

Mathias Kuhring
Mathias Kuhring

Reputation: 13

An alternative to using mode is to use class:

class(foo) %in% c("character", "complex", "integer", "logical", "numeric")

This would prevent matching lists as well as factors and matrices. Note the explicit listing of integer, since as a class it won't match with numeric. Just wrap that in a little function, if you need to use it more often.

Upvotes: 1

Diego Aviles
Diego Aviles

Reputation: 106

Perhaps not the optimal, but it will do the work: check if the variable is a vector AND if it's not a list. Then you'll bypass the is.vector result:

if(is.vector(someVector) & !is.list(someVector)) { 
  do something with the vector 
}

Upvotes: 8

Joshua Ulrich
Joshua Ulrich

Reputation: 176648

There are only primitive functions, so I assume you want to know if the vector is one of the atomic types. If you want to know if an object is atomic, use is.atomic.

is.atomic(logical())
is.atomic(integer())
is.atomic(numeric())
is.atomic(complex())
is.atomic(character())
is.atomic(raw())
is.atomic(NULL)
is.atomic(list())        # is.vector==TRUE
is.atomic(expression())  # is.vector==TRUE
is.atomic(pairlist())    # potential "gotcha": pairlist() returns NULL
is.atomic(pairlist(1))   # is.vector==FALSE

If you're only interested in the subset of the atomic types that you mention, it would be better to test for them explicitly:

mode(foo) %in% c("logical","numeric","complex","character")

Upvotes: 35

Related Questions