Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R: find vector in list of vectors

Tags:

find

list

r

vector

i'm working with R and my goal is to check wether a given vector is in a list of unique vectors.

The list looks like

final_states <- list(c("x" = 5, "y" = 1),
                 c("x" = 5, "y" = 2),
                 c("x" = 5, "y" = 3),
                 c("x" = 5, "y" = 4),
                 c("x" = 5, "y" = 5),
                 c("x" = 3, "y" = 5))

Now I want to check wether a given state is in the list. For example:

state <- c("x" = 5, "y" = 3)

As you can see, the vector state is an element of the list final_states. My idea was to check it with %in% operator:

state %in% final_states

But I get this result:

[1] FALSE FALSE

Can anyone tell me, what is wrong?

Greets, lupi

like image 836
lupi5 Avatar asked Jan 31 '15 17:01

lupi5


People also ask

Can you have a vector of lists in R?

Almost all data in R is stored in a vector, or even a vector of vectors. A list is a recursive vector: a vector that can contain another vector or list in each of its elements. Lists are one of the most flexible data structures in R.

How do I search a vector in R?

To summarize, to search an unsorted vector for a single target value, a good choice is to use the %in% operator. To search for multiple target values, you can use the is. element function, which returns results as a logical vector, or use the similar match function, which returns an integer vector.

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

To check if specific item is present in a given list in R language, use %in% operator. %in% operator returns TRUE if the item is present in the given list, or FALSE if not.


1 Answers

If you just want to determine if the vector is in the list, try

Position(function(x) identical(x, state), final_states, nomatch = 0) > 0
# [1] TRUE

Position() basically works like match(), but on a list. If you set nomatch = 0 and check for Position > 0, you'll get a logical result telling you whether state is in final_states

like image 124
Rich Scriven Avatar answered Sep 24 '22 13:09

Rich Scriven