Reputation: 199
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:
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!
Upvotes: 0
Views: 96
Reputation: 886938
An option with 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
Upvotes: 0
Reputation: 3194
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
Upvotes: 1