I have this df1:
A B C
1 2 3
5 7 9
where A B C
are columns names.
I have another df2 with one column:
A
1
Data:
df1 <- data.frame(A=c(1,5),
B=c(2,7),
C=c(3,9))
df2 <- data.frame(A=c(1,2,3,4))
Solution:
df2 <- matrix(rep(df2$A, ncol(df1)), ncol=ncol(df1))
colnames(df2) <- colnames(df1)
rbind(df1,df2)
Result:
A B C 1 1 2 3 2 5 7 9 3 1 1 1 4 2 2 2 5 3 3 3 6 4 4 4
By analogy with @useR's excellent Base R answer, here's a tidyverse
solution:
library(purrr)
map2_df(df1, df2, c)
A B C 1 1 2 3 2 5 7 9 3 1 1 1 4 2 2 2 5 3 3 3 6 4 4 4
Here are a few other (less desirable) options from when I first answered this question.
library(dplyr)
bind_rows(df1, df2 %>% mutate(B=A, C=A))
Or, if we want to dynamically get the number of columns and their names from df1:
bind_rows(df1,
df2[,rep(1,ncol(df1))] %>% setNames(names(df1)))
And one more Base R method:
rbind(df1, setNames(df2[,rep(1,ncol(df1))], names(df1)))
For the sake of completeness, here is data.table
approach which doesn't require to handle column names:
library(data.table)
setDT(df1)[, lapply(.SD, c, df2$A)]
A B C 1: 1 2 3 2: 5 7 9 3: 1 1 1 4: 2 2 2 5: 3 3 3 6: 4 4 4
Note that the OP has described df2
to consist only of one column.
There is also a base R version of this approach:
data.frame(lapply(df1, c, df2$A))
A B C 1 1 2 3 2 5 7 9 3 1 1 1 4 2 2 2 5 3 3 3 6 4 4 4
This is similar to d.b's approach but doesn't required to deal with column names.