Anika Masters
2013-Feb-26 16:34 UTC
[R] combining 2 dataframes into a 3rd df, with 1 row for each row in df1 & df2
# '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> df1a b d 1 7 99 12> df2d b x y c 1 88 34 12 44 56> mydfa b c d x y [1,] "7" "99" "na" "12" "na" "na" [2,] "na" "34" "56" "88" "12" "44"
Anika Masters
2013-Feb-26 16:38 UTC
[R] combining 2 dataframes into a 3rd df, with 1 row for each row in df1 & df2
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"