How to test if object is a vector

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 
}

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

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")

Tags:

Object

R

Vector