Find entire row in R data frame?

Viewed 1048

I have a large dataframe df with 10 columns.

For example:

col1 col2 col3 col4 col5 col6 ......
a    22   13   dd   kuku ppp
q    123  444  dff  pupu sds

I get a new record rec1 with the same structure (10 columns):

rec1 <-  col1 col2 col3 col4 col5 col6 ......
         a    22   13   dd   kuku ppp

I want to search df and return true/false if I have found this row or not. Please advise how to do this? Dplyr filter?

2 Answers
# sample data
df = mtcars
my_row = mtcars[10,]

Option 1: Use apply to find a row that matches all values in your row.

any(apply(df,1,function(x) {all(x==my_row)}))

Option 2: create an index by pasting all columns per row, then match against that.

index = do.call("paste", mtcars)
do.call('paste',my_row) %in% index

Both return TRUE. Hope this helps!

One way would be to use row.match from the prodlim package.

!is.na(row.match(rec1, df))

A bit of a workaround with a dplyr::semi_join. And then check if there are more than 0 rows.

require(dplyr)

nrow(semi_join(df, rec1)) > 0  
Related