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
2
3
4
I would like to append df2 for each column of df1, creating this final dataframe:
A B C
1 2 3
5 7 9
1 1 1
2 2 2
3 3 3
4 4 4
is it possible to do it?
DATA
A solution from
purrr
, which usesmap_dfc
to loop through all columns indf1
to combine all the elements withdf2$A
.Data
Here is a base R method with
rbind
,rep
, andsetNames
:Edit: turns out
data.frame
isn't necessary:will work.
data
For the sake of completeness, here is
data.table
approach which doesn't require to handle column names:Note that the OP has described
df2
to consist only of one column.There is also a base R version of this approach:
This is similar to d.b's approach but doesn't required to deal with column names.
By analogy with @useR's excellent Base R answer, here's a
tidyverse
solution:Here are a few other (less desirable) options from when I first answered this question.
Or, if we want to dynamically get the number of columns and their names from df1:
And one more Base R method:
We can use
base R
methodsdata