Check if the value is in the data frame

I am trying to check if any particular value is in the data frame.

I know that an operator %in%should allow me to do this, but it does not work as I would expect when applied to the entire data frame:

A = data.frame(B=c(1,2,3,4), C=c(5,6,7,8))
1 %in% A

[1] FALSE

But if I applied this to a specific column, the value in it works as I expect:

1 %in% A$C

[1] TRUE

What is the correct way to check if any value is in the data frame?

+4
source share
6 answers

You can do:

any(A==1)
#[1] TRUE

OR with Reduce:

Reduce("|", A==1)

OR

length(which(A==1))>0

OR

is.element(1,unlist(A))
+6
source

Or simply

sum(A == 1) > 0
#[1] TRUE
+7
source

sapply, any.

any(sapply(A, function(x) 1 %in% x))
[1] TRUE

digEmAll, unlist, (data.frame) .

1 %in% unlist(A)
[1] TRUE
+4
source

To find the location of this value, you can do f.ex:

which(A == 1, arr.ind=TRUE)
#     row col
#[1,]   1   1
+3
source

The trick to understanding why your first attempt is not working really comes down to understanding what a data frame is, namely a list of vectors of equal length. What you are trying to do here does not check if this list of vectors matches your condition, but checks if the values ​​in these vectors match the condition.

+2
source

Try:

any(A == 1)

Returns false or true

0
source

Source: https://habr.com/ru/post/1674102/


All Articles