Kewl
Kewl

Reputation: 3417

Check if value is in data frame

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

Answers (6)

gonzalez.ivan90
gonzalez.ivan90

Reputation: 1360

Try:

any(A == 1)

Returns FALSE or TRUE

Upvotes: 1

989
989

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

AkselA
AkselA

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

WHoekstra
WHoekstra

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

Sotos
Sotos

Reputation: 51592

Or simply

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

Upvotes: 8

lmo
lmo

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

Related Questions