Reputation: 3417
I'm trying to check if a specific value is anywhere in a data frame.
I know the %in%
operator should allow me to do this, but it doesn't seem to work the way I would expect when applying to a whole 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 apply this to the specific column the value is in it works the way I expect:
1 %in% A$C
[1] TRUE
What is the proper way of checking if a value is anywhere in a data frame?
Upvotes: 17
Views: 67029
Reputation: 12935
You could do:
any(A==1)
#[1] TRUE
OR with Reduce
:
Reduce("|", A==1)
OR
length(which(A==1))>0
OR
is.element(1,unlist(A))
Upvotes: 25
Reputation: 8846
To find the location of that value you can do f.ex:
which(A == 1, arr.ind=TRUE)
# row col
#[1,] 1 1
Upvotes: 10
Reputation: 173
The trick to understanding why your first attempt doesn't work, really comes down to understanding what a data frame is - namely a list of vectors of equal length. What you're trying to do here is not check if that list of vectors matches your condition, but checking if the values in those vectors matches the condition.
Upvotes: 3
Reputation: 38520
Loop through the variables with sapply
, then use any
.
any(sapply(A, function(x) 1 %in% x))
[1] TRUE
or following digEmAll's comment, you could use unlist
, which takes a list (data.frame) and returns a vector.
1 %in% unlist(A)
[1] TRUE
Upvotes: 6