Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test if object is a vector

Tags:

object

r

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?

like image 913
Jeroen Ooms Avatar asked Oct 21 '13 17:10

Jeroen Ooms


People also ask

How do you know if its a vector?

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

How do you check if something is in a vector in R?

%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.

How do you check if an object is a list in R?

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.

How do you check if a string is in a vector of strings in R?

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.


2 Answers

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") 
like image 165
Joshua Ulrich Avatar answered Sep 20 '22 04:09

Joshua Ulrich


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  } 
like image 40
Diego Aviles Avatar answered Sep 20 '22 04:09

Diego Aviles