Skip to content

Comparing data frames and keeping non-matches

2 messages · Pele

#
Hi R users,

I am trying to compare 2 data frames by  subject and match and save the no
matches to an object called nomatch, but I am getting unexpected results...
Can anyone tell me how to correct the code to get the expected results shown
in the last table?

Many thanks in advance for your any help!

library("reshape")

year <- c(2100:2110)
x1 <- c(F,T,T,F,F,F,T,F,T,T,F)
df1 <- data.frame(cbind(year, x1)) 
df1$subject <- c(1,1,1,2,2,3,3,3,3,4,4)
df1$match <- 1; df1

df2 <- data.frame(cbind(year, x1))
df2$subject <- c(1:11)
df2$match <- 1; df2
key <- c("subject", "match")

nomatch <- subset(df2, is.element(df2[,key], df1[,key])==FALSE); nomatch
rm(list=ls())

Unexpected Results
    year x1 subject match
1  2100  0       1     1
3  2102  1       3     1
5  2104  0       5     1
7  2106  1       7     1
9  2108  1       9     1
11 2110  0      11     1


Results I expected

   year x1 subject match
5  2104  0       5     1
6  2105  0       6     1
7  2106  1       7     1
8  2107  0       8     1
9  2108  1       9     1
10 2109  1      10     1
11 2110  0      11     1
#
Hi All,

I found a solution that give the correct answer..

year <- c(2100:2110)
x1 <- c(F,T,T,F,F,F,T,F,T,T,F)
df1 <- data.frame(cbind(year, x1)) 
df1$subject <- c(1,1,1,2,2,3,3,3,3,4,4)
df1$match <- 1
df1$key <- paste(df1$subject, df1$match, sep="") ; df1

df2 <- data.frame(cbind(year, x1))
df2$subject <- c(1:11)
df2$match <- 1
df2$key <- paste(df2$subject, df2$match, sep="") ; df2


nomatch <- subset(df2, is.element(df2[,"key"], df1[,"key"])==FALSE); nomatch
rm(list=ls())
Pele wrote: