1
votes

I have a data frame df1 with three columns called x, y and z

df1
x y z
8 2 8
9 3 1
1 7 2

I also have a list that contains 30 data frames df2, df3, ... df31, that each have three columns a, b and c.

list1
df2        df3        ...      df31
a b c      a b c               a b c 
4 7 5      4 8 6               3 1 7 
9 5 3      3 1 9               4 8 6
8 6 1      2 9 1               1 6 3

I want to merge column y of df1 with each data frame in the list as a new column. So the new list should look like this:

list2
df2          df3          ...      df31
a b c y      a b c y               a b c y 
4 7 5 2      4 8 6 2               3 1 7 2 
9 5 3 3      3 1 9 3               4 8 6 3
8 6 1 7      2 9 1 7               1 6 3 7

I have been using the following code:

list2 <- mapply("cbind", list1, df1$y, SIMPLIFY = FALSE)

however this only seems to take the first value of y and puts it into the new column:

list2
df2          df3          ...      df31
a b c y      a b c y               a b c y 
4 7 5 2      4 8 6 2               3 1 7 2 
9 5 3 2      3 1 9 2               4 8 6 2
8 6 1 2      2 9 1 2               1 6 3 2

This seems like an easy problem and I am just really stuck with it so I would appreciate any help. Thanks!

1
You need list(df1$y) or df1['y']akrun

1 Answers

3
votes

As we need the 'y' column as a whole, it can be wrapped in a list. Otherwise, it would loop through each element of the column (also possibly there would be warnigns as well because the length won't match)

Map(cbind, list1, y = list(df1$y))

Or

mapply(cbind, list1, y = list(df1$y), SIMPLIFY = FALSE)

Also, this can be done easily with lapply

lapply(list1, transform, y = df1$y)