-1

我有 2 个要比较的数据框。(我已经在这里问过这个问题,但是为了提高效率,我用不同的措辞:How to find Differences in elements of 2 data frames based on 2 unique identifiers

df1<-data.frame(DS.ID=c(123,214,543,325,123,214),OP.ID=c("xxab","xxac","xxad","xxae","xxaf","xxaq"),P.ID=c("AAC","JGK","DIF","ADL","AAC","JGR"),date="20121111")

> df1
   DS.ID OP.ID P.ID     date
1   123  xxab  AAC 20121111
2   214  xxac  JGK 20121111
3   543  xxad  DIF 20121111
4   325  xxae  ADL 20121111
5   123  xxaf  AAC 20121111
6   214  xxaq  JGR 20121111

df2<-data.frame(DS.ID=c(123,214,543,325,123,214),OP.ID=c("xxab","xxac","xxad","xxae","xxaf","xxaq"),P.ID=c("AAC","JGK","DIF","ADL","AAC","JGS"),date="20121110")

> df2
  DS.ID OP.ID P.ID     date
1   123  xxab  AAC 20121110
2   214  xxac  JGK 20121110
3   543  xxad  DIF 20121110
4   325  xxae  ADL 20121110
5   123  xxaf  AAC 20121110
6   214  xxaq  JGS 20121110

唯一id是基于DS.ID和OP.ID的组合,所以DS.ID可以重复,但是DS.ID和OP.ID的组合不会。我想找到 P.ID 发生变化的实例。此外,DS.ID 和 OP.ID 的组合不一定在同一行。

所以,首先我会 rbind 创建一个数据框,然后我想与 dcast 融为一体。我希望以 DS.ID 和 OP.ID 列作为唯一 ID,然后将两个日期的列与每个日期的值对应起来。

df12         <- rbind.fill(df1,df2)
4

1 回答 1

2

如果您只想在 P.ID 有差异时进行比较,您可以只merge通过两个常见的列,然后比较:

# Convert from factor to character.
df1$P.ID<-as.character(df1$P.ID)
df2$P.ID<-as.character(df2$P.ID)

# Merge 
compare.df<-merge(df1,df2,by=c('DS.ID','OP.ID'))
# Find differences.
compare.df[compare.df$P.ID.x!=compare.df$P.ID.y,]
#   DS.ID OP.ID P.ID.x   date.x P.ID.y   date.y
# 4   214  xxaq    JGR 20121111    JGS 20121110
于 2013-11-11T21:26:19.543 回答