Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Paste 2 data frames side by side without any key

I have two data frames

A   B    E   H  
x1  x2  x3  x6  
x1  x2  x4  x7  
x1  x2  x5  x8  

and

A   B     
y1  y2    
y1  y2     

and this is what i would like to achieve with dplyr or reshape2

A   B    E   H  A   B   
x1  x2  x3  x6  y1  y2  
x1  x2  x4  x7  y1  y2   
x1  x2  x5  x8      

Thanks

like image 528
Ian.T Avatar asked Aug 16 '26 23:08

Ian.T


1 Answers

If the number of rows are same use

cbind(df1, df2)
#   A  B  E  H  A  B
#1 x1 x2 x3 x6 y1 y2
#2 x1 x2 x4 x7 y1 y2
#3 x1 x2 x5 x8 y1 y2

Or in dplyr

library(dplyr)
library(stringr)
df2 %>% 
       rename_all(~ str_c(., ".1")) %>%
       bind_cols(df1, .)

In some versions of dplyr (0.8.5), it would rename correctly when there are duplicate column names

bind_cols(df1, df2)

NOTE: It is not recommended to have same column names in data.frame so we could change the column names with make.unique


If we have two datasets with unequal number of rows

library(rowr)
cbind.fill(df1, df2new, fill = NA)
#   A  B  E  H    A    B
#1 x1 x2 x3 x6   y1   y2
#2 x1 x2 x4 x7   y1   y2
#3 x1 x2 x5 x8 <NA> <NA>

Or with base R

mxn <- max(nrow(df1), nrow(df2new))
df2new[(nrow(df2new)+1):mxn,] <- NA
cbind(df1, df2new)
#   A  B  E  H    A    B
#1 x1 x2 x3 x6   y1   y2
#2 x1 x2 x4 x7   y1   y2
#3 x1 x2 x5 x8 <NA> <NA>

data

df1 <- structure(list(A = c("x1", "x1", "x1"), B = c("x2", "x2", "x2"
), E = c("x3", "x4", "x5"), H = c("x6", "x7", "x8")),
    class = "data.frame", row.names = c(NA, 
-3L))

df2 <- structure(list(A = c("y1", "y1", "y1"), B = c("y2", "y2", "y2"
)), class = "data.frame", row.names = c(NA, -3L))

df2new <- structure(list(A = c("y1", "y1"), B = c("y2", "y2")), class = "data.frame", row.names = c(NA, 
-2L))
like image 54
akrun Avatar answered Aug 18 '26 21:08

akrun



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!