使用R比较具有不同行的两个数据帧

时间:2021-01-21 22:53:53

I have two data frames with different row numbers:

我有两个不同行号的数据框:

class1<-c(1,2,5,6,7)
abund1<-c(10.4,7.5,7.1,5.1,3.2)
df1<-data.frame(class1,abund1)

class2<-c(1,2,3,4,5,6,7)
abund2<-c(9.5,8.4,8,6.3,6,2.4,1.2)
df2<-data.frame(class2,abund2)

I would like to compare these two data frames but I would need the same number of rows. My purpose is to fill by zero all those classes which do not match with the df2. The solution would be as it follows:

我想比较这两个数据帧,但我需要相同的行数。我的目的是将所有那些与df2不匹配的类填充为零。解决方案如下:

  class abund
     1   10.4
     2    7.5
     3    0.0
     4    0.0
     5    7.1
     6    5.1
     7    3.2

Any ideas? Thank you so much!

有任何想法吗?非常感谢!

2 个解决方案

#1


1  

kk<-merge(df1,df2,by.x="class1",by.y="class2",all.y=TRUE)[-3]
kk[is.na(kk$abund1),2]<-0
> kk
  class1 abund1
1      1   10.4
2      2    7.5
3      3    0.0
4      4    0.0
5      5    7.1
6      6    5.1
7      7    3.2

#2


0  

An option with data.table

data.table的选项

 library(data.table)#v1.9.5+
 setDT(df1, key='class1')[df2][is.na(abund1), abund1:=0][, abund2:=NULL][]
 #   class1 abund1
 #1:      1   10.4
 #2:      2    7.5
 #3:      3    0.0
 #4:      4    0.0
 #5:      5    7.1
 #6:      6    5.1
 #7:      7    3.2

#1


1  

kk<-merge(df1,df2,by.x="class1",by.y="class2",all.y=TRUE)[-3]
kk[is.na(kk$abund1),2]<-0
> kk
  class1 abund1
1      1   10.4
2      2    7.5
3      3    0.0
4      4    0.0
5      5    7.1
6      6    5.1
7      7    3.2

#2


0  

An option with data.table

data.table的选项

 library(data.table)#v1.9.5+
 setDT(df1, key='class1')[df2][is.na(abund1), abund1:=0][, abund2:=NULL][]
 #   class1 abund1
 #1:      1   10.4
 #2:      2    7.5
 #3:      3    0.0
 #4:      4    0.0
 #5:      5    7.1
 #6:      6    5.1
 #7:      7    3.2