问题
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?
回答1:
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")
回答2:
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
}
回答3:
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.
来源:https://stackoverflow.com/questions/19501186/how-to-test-if-object-is-a-vector