0

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!

2
  • What did you try so far? Commented Jul 6, 2015 at 3:21
  • I tried to use the merge function but I don't know how to fill the empty classes by 0. Commented Jul 6, 2015 at 3:30

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for your quick and rigth answer @user227710!
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.