[R] combining 2 dataframes into a 3rd df, with 1 row for each row in df1 & df2

Anika Masters anika.masters at gmail.com
Tue Feb 26 17:38:57 CET 2013


df1 <- data.frame(matrix(data=c(7, 99, 12) ,  nrow=1 ,  dimnames =
list( NULL ,  c('a' , 'b' , 'd') ) ) )

df2 <- data.frame(matrix(data=c(88, 34, 12, 44, 56) ,  nrow=1
,dimnames = list( NULL ,  c('d' , 'b' , 'x' ,  'y', 'c') ) ) )

I figured it out.
mydf <- merge(df2,df1,all.y=T, all.x=T)
mydf2 <- mydf[,sort(names(mydf))]

On Tue, Feb 26, 2013 at 8:34 AM, Anika Masters <anika.masters at gmail.com> wrote:
> # 'I need help combining 2 dataframes (df1 & df2) into a 3rd (mydf).
> I want the 3rd dataframe to contain 1 row for each row in df1 & df2,
> and all the columns in both df1 & df2. # Advice is appreciated. Thank
> you.
>
> df1 <- data.frame(matrix(data=c(7, 99, 12) ,  nrow=1 ,  dimnames =
> list( NULL ,  c('a' , 'b' , 'd') ) ) )
>
> df2 <- data.frame(matrix(data=c(88, 34, 12, 44, 56) ,  nrow=1 ,
> dimnames = list( NULL ,  c('d' , 'b' , 'x' ,  'y', 'c') ) ) )
>
> mydf <- matrix(data = c(7, 99, 'na', 12, 'na', 'na', 'na',
> '34','56','88','12','44') , nrow=2 ,  byrow = T, dimnames = list( NULL
> ,  c('a' , 'b' , 'c' ,  'd', 'x' , 'y' ) ) )
>
> df1
> df2
> mydf
>
>
>> df1
>   a  b  d
> 1 7 99 12
>
>> df2
>    d  b  x  y  c
> 1 88 34 12 44 56
>
>> mydf
>      a    b    c    d    x    y
> [1,] "7"  "99" "na" "12" "na" "na"
> [2,] "na" "34" "56" "88" "12" "44"



More information about the R-help mailing list