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