Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rbind two tables and fill NA's rows with values having same variable

Tags:

r

im going to explain to you my question on base of the sample data. Here is first table (df1):

  x x1 y  z
1 1 10 a 11
2 3 11 b 13
3 5 10 c 15
4 7 11 d 17
5 9 10 e 19

here is a dput() version:

structure(list(x = c(1, 3, 5, 7, 9), x1 = c(10, 11, 10, 11, 10
), y = structure(1:5, .Label = c("a", "b", "c", "d", "e"), class = "factor"), 
    z = c(11, 13, 15, 17, 19)), .Names = c("x", "x1", "y", "z"
), row.names = c(NA, -5L), class = "data.frame")

and second table (df2):

  x x1
1 2 10
2 3 60

dput():

structure(list(x = c(2, 3), x1 = c(10, 60)), .Names = c("x", 
"x1"), row.names = c(NA, -2L), class = "data.frame")

I need to now bind rows of these two tables and fill the missing column values with values from df1. Let me explain you on base of these two tables.

At first i use smartbind() function from gtools library:

library(gtools)
data <- smartbind(df1, df2)

And the result that i get looks like that:

 x x1    y  z
 1 10    a 11
 3 11    b 13
 5 10    c 15
 7 11    d 17
 9 10    e 19
 2 10 <NA> NA
 3 60 <NA> NA

So i would like to fill up the all NA values which appear in the rows from df2, with df1 values if the x is the same. In this case it would look like that:

 x x1    y  z
 1 10    a 11
 3 11    b 13
 5 10    c 15
 7 11    d 17
 9 10    e 19
 2 10 <NA> NA
 3 60    b 13

In my original dataset i do have around 280 columns! Thanks for help

Is there any more ELEGANT way to do it rather then joining two data frames and then using rbind()

like image 236
Mal_a Avatar asked Feb 18 '26 22:02

Mal_a


1 Answers

First you can merge missing columns of df2 from df1, only keeping extra columns( y and z, and the key column x from df1):

df2 = merge(df2,df1[,c("x","y","z")],by="x",all.x=T)

and then rbind df1 and df2:

> rbind(df1,df2)
  x x1    y  z
1 1 10    a 11
2 3 11    b 13
3 5 10    c 15
4 7 11    d 17
5 9 10    e 19
6 2 10 <NA> NA
7 3 60    b 13
like image 80
tyumru Avatar answered Feb 20 '26 11:02

tyumru