Asif Shakeel
Asif Shakeel

Reputation: 135

R: selective fill of a column from another

I have two dataframes with same column names, but different lengths. Example:

sf<-data.frame(a=c(1,5,9),b=c(2,6,4))  
sf  
  a b  
1 1 2  
2 5 6  
3 9 4  



lf<-data.frame(a=1:10,b=rep(0,10))  
lf  
    a b  
1   1 0  
2   2 0  
3   3 0  
4   4 0  
5   5 0  
6   6 0  
7   7 0  
8   8 0  
9   9 0  
10 10 0 

I would like to fill in values of lf$b with values in sf$b where their a columns are identical (i.e. where sf$a equals lf$a). Thus, the result should be:

    a b  
1   1 2  
2   2 0  
3   3 0  
4   4 0  
5   5 6  
6   6 0  
7   7 0  
8   8 0  
9   9 4  
10 10 0 

Is there a quick way to do this in R?

Thanks!

Upvotes: 1

Views: 87

Answers (2)

akrun
akrun

Reputation: 886938

Here is an option using data.table

library(data.table)
setkey(setDT(sf),a)[lf][is.na(b), b:=i.b][, i.b:=NULL][]
#      a b
#  1:  1 2
#  2:  2 0
#  3:  3 0
#  4:  4 0
#  5:  5 6
#  6:  6 0
#  7:  7 0
#  8:  8 0
#  9:  9 4
# 10: 10 0

Or a base R option

transform(merge(lf, sf, by='a', all=TRUE), b= ifelse(is.na(b.y),
                     b.x,b.y))[-c(2:3)]

Upvotes: 1

divide_by_zero
divide_by_zero

Reputation: 1027

If you mean for sf$a to refer to the row index of lf, then the following should work:

lf[sf$a, ]$b = sf$b

However, if you mean to update rows in lf where lf$a matches sf$a, then you can do something like:

lf[lf$a %in% sf$a, ]$b = sf$b

Upvotes: 2

Related Questions