Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Existing function for seeing if a row exists in a data frame?

Tags:

r

Is there an existing function for determining whether a row exists within a data frame? I suppose could do an apply/identical, but it seems like I'm missing something.

For example:

given such a data frame:

  a   b
1 1 cat
2 2 dog

Is there an existing function which will allow me to test whether the row (1, cat) exists in the data frame?

Thanks, Zach

like image 751
Zach Avatar asked May 06 '11 20:05

Zach


4 Answers

Try match_df from plyr (using Marek's sample data):

library(plyr)
X <- data.frame(a=1:2, b=c("cat","dog"))
row_to_find <- data.frame(a=1, b="cat")

match_df(X, row_to_find)
like image 162
hadley Avatar answered Sep 30 '22 15:09

hadley


For data from @Marek answer.

nrow(merge(row_to_find,X))>0 # TRUE if exists
like image 43
Wojciech Sobala Avatar answered Sep 30 '22 15:09

Wojciech Sobala


Taking your example:

X <- data.frame(a=1:2, b=c("cat","dog"))
row_to_find <- data.frame(a=1, b="cat") # it has to be data.frame (not a vector) to hold different types

Then

duplicated(rbind(X, row_to_find))[nrow(X)+1]

gives you answer.

like image 7
Marek Avatar answered Sep 30 '22 14:09

Marek


I suggest Ben Bolker's solution since nrow(merge(row_to_find,X))>0 solution doesn't work for me (always give TRUE) :

tail(duplicated(rbind(X,row_to_find)),1)>0
like image 1
Laurent Camus Avatar answered Sep 30 '22 16:09

Laurent Camus