star star - 2 months ago 21
R Question

How can compare value of two table?

I have two data frame like below, I would like to compare value of these table together (based on same rows and colnames) and specified same values with TRUE otherwise with FALSE.

data1:

id A B C
m1 2 2 2
m2 2 1 2

data2:

id A D B
m1 1 2 2
m2 2 3 2


Output:

id A B
m1 FALSE TRUE
m2 TRUE FALSE

Answer

You can merge the two data frames after melting by id to find the intersecting columns. Then generate a new column with the equality condition for the values. Finally dcast back to wide format for your output table:

library(reshape2)
df1 <- melt(data1,"id")
df2 <- melt(data2,"id")
df3 <- merge(df1,df2,by=c("id","variable"))
df3$value <- df3$value.x == df3$value.y
result <- dcast(df3, id~variable)
##id     A     B
##1 m1 FALSE  TRUE
##2 m2  TRUE FALSE
Comments