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?
To check if a vector exists in a list, we can use %in%, and read the vector as list using list function. For example, if we have a list called LIST and a vector called V then we can check whether V exists in LIST using the command LIST %in% list(V).
%in% operator can be used in R Programming Language, to check for the presence of an element inside a vector. It returns a boolean output, evaluating to TRUE if the element is present, else returns false.
list() Function. is. list() function in R Language is used to return TRUE if the specified data is in the form of list, else returns FALSE.
Find String Matches in a Vector or Matrix in R Programming – str_detect() Function. str_detect() Function in R Language is used to check if the specified match of the substring exists in the original string. It will return TRUE for a match found otherwise FALSE against each of the element of the Vector or matrix.
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")
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 }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With