在R中将新数据获取到旧数据框中

时间:2018-12-13 18:05:12

标签: r

将新数据数据帧转换为旧数据帧时,我遇到了OD问题。

old<-data.frame(O=c("I","A","B","D","R","F","A"),D=c("I","F","C","B","D","G","B"),F3=c(1:7))
new<-data.frame(O=c("F","D","R","F","A"),D=c("G","B","D","G","F"),F3=c(11,0,13,14,16))
old$OD<-paste(old$O, old$D, sep=" ")
new$OD<-paste(new$O, new$D, sep=" ")

旧数据:

> old
  O D F3  OD
1 I I  1 I I
2 A F  2 A F
3 B C  3 B C
4 D B  4 D B
5 R D  5 R D
6 F G  6 F G
7 A B  7 A B

和新的:

> new
  O D F3  OD
1 F G 11 F G
2 D B  0 D B
3 R D 13 R D
4 F G 14 F G
5 A F 16 A F

我想基于普通OD用新的值替换旧的F3值。

我尝试过:

Old_new1<-merge(old,new, by = "OD")


Old_new2<- ifelse(old$OD %in%  new$OD,new$F3,old$F3 )
Old_new2<-data.frame(old,Old_new2)

我想得到:

> old_new
      O D F3  OD F3_new
    1 I I  1 I I  1
    2 A F  2 A F 16
    3 B C  3 B C  3
    4 D B  4 D B  0
    5 R D  5 R D 13
    6 F G  6 F G 14
    7 A B  7 A B  7

我想成为替代者,首先去做。

谢谢!

1 个答案:

答案 0 :(得分:1)

我们可以使用last data.table join的'OD'并在'new'({{1} })移至“旧”中的“ F3”列

on