Whether one element in a dataframe

I find an little but interesting question. How could we know if an element in a dataframe in R, especially there are many data? I attach an example, and find two methods could do it. Are there other ways and thought? Any help would be appreciated.

10.4 %in% n4$n2
10.4 %in% as.matrix(n4)

Created on 2023-05-28 with reprex v2.0.2

Whenever dealing with variables that are all numeric, a matrix is almost always the good choice.

d <- data.frame(n1 = c(7.3,12.5,18.4,15.0,11.8,13.7,10.2,9.5,7.6,2.5),
                n2 = c(5.2,6.0,5.5,2.0,NA,6.7,5.6,3.5,10.4,6.8),
                n3 = c(5.6,5.8,13.3,13.8,3.0,10.1,10.7,7.7,12.3,15.8))

# avoids explicit conversion to a matrix
10.4 %in% unlist(d)
#> [1] TRUE

# abstraction
is_there <- function(x,y) x %in% unlist(y)
#> [1] TRUE

Created on 2023-05-27 with reprex v2.0.2

1 Like

It works!!! Thank you.

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.