在数据帧之间匹配成对的列数据

时间:2018-07-11 02:04:08

标签: r replace key match multiple-columns

我有一个基于不良事件的类别和子类别的具有不良医学事件数字代码的患者的数据框df1。子类代码(例如3)可以表示不同的东西,具体取决于类(Class 4子类3与Class 5子类3不同)。

ID = c(2, 2, 2, 2, 3, 5) 
Class = c(4,4,4,5,5,5)
Subclass = c(1,2,3,1,2,3)
df1 = data.frame(ID, Class, Subclass)

  ID Class Subclass
1  2     4        1
2  2     4        2
3  2     4        3
4  2     5        1
5  3     5        2
6  5     5        3

数据帧df2是不良事件的代码键

Class = c(4,4,4,5,5,5)
Subclass = c(1,2,3,1,2,3)
Class.description = c("Heart", "Heart", "Heart", "Lung", "Lung", "Lung")
Subclass.description = c("pericarditis", "myocarditis", "endocarditis", "asthma", "pneumonia", "COPD")
df2 = data.frame(Class, Subclass, Class.description, Subclass.description)
df2

     Class Subclass Class.description Subclass.description
1     4        1             Heart         pericarditis
2     4        2             Heart          myocarditis
3     4        3             Heart         endocarditis
4     5        1              Lung               asthma
5     5        2              Lung            pneumonia
6     5        3              Lung                 COPD

我想匹配数据帧,使df1如下所示:

  ID     Class        Subclass
1  2     Heart        pericarditis
2  2     Heart        myocarditis
3  2     Heart        endocarditis
4  2     Lung         asthma
5  3     Lung         pneumonia
6  5     Lung         COPD

有什么建议吗?

1 个答案:

答案 0 :(得分:0)

df_new = merge(df1,df2,by=c("Class","Subclass"));