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
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>
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))