combine vector to data frame by rownames filling gaps with zeros

2.7k views Asked by At

i have the following conundrum. I have a dataframe x that looks like:

     v2      v3    
10   4.0      3.0
11   5.0      3.0
12   6.0      9.0
13   5.0      6.0    # where 10-14 are rownames
14   3.0      6.0

and then the datafame y:

     value        
11   99            
13   88      #where 11,13,14 are row names
14   33

I would like to add value to x matching the rownames and filling the gaps with zeros.i.e.:

      v2      v3    value
10   4.0      3.0     0
11   5.0      3.0     99
12   6.0      9.0      0
13   5.0      6.0     88
14   3.0      6.0     33

Although if I have to fill with NAs maybe I can do this and then change NAs to zeros within the new y vector afterwards.

I have been trying variations of rbind.fill from plyr using newDF<-do.call(rbind.fill)but nothing i am achieving is working out the way i hope.

EDIT i GOT IT TO GIVE NAS USING merge(x,y,all=TRUE,by='row.names')

2

There are 2 answers

1
smu On BEST ANSWER

I would do it like that:

y$row <- rownames(y)    # add a 'helper' column for the merge function.
x$row <- rownames(x)
n <-merge(x,y, by='row', all=T)
n <- n[,-1]    # remove the 'helper' column

and then replace the NAs by 0:

n[is.na(n$value),]$value = 0

But this fails, or will procude wrong results, if you have NAs in your y/x dataframe.

0
Tyler Rinker On

If it's just one column this is another approach though likely not the best one but an alternative:

x$value <- ifelse(rownames(x) %in% rownames(y), y$value, 0)