codedancer
codedancer

Reputation: 1634

Assign new columns to a list of dataframes from a second dataframe in R

I have a list of dataframes df_list and a second dataframe df_new. I want to add the 1st column a of df_new into the 1st dataframe mtcars1 in the list df_list, the 2nd column b of df_new into the 2nd dataframe mtcars2 in the list df_list, and so on.

The expected result: In the df_list, mtcars1 will have a new column a from df_new, mtcars2 will have a new column b from df_new, mtcars3 will have a new column c from df_new, mtcars4 will have a new column c from df_new.

What's the best way to do this in a function or loop?

library(tidyverse)
df_list <- list(mtcars, mtcars, mtcars, mtcars)
names(df_list) <- c("mtcars1", "mtcars2", "mtcars3", "mtcars4")
df_new <- mtcars[1:4] %>% rename(a = mpg, b = cyl, c = disp, d = hp)

Upvotes: 1

Views: 39

Answers (2)

zx8754
zx8754

Reputation: 56249

Using Map:

Map(cbind, df_list, df_new)

If we need to keep the names, then write custom function:

myCbind <- function(x, y){
  d <- cbind(x, df_new[[ y ]])
  colnames(d)[ ncol(d) ] <- y
  d
  }

Map(myCbind, df_list, colnames(df_new))

Check the names:

res <- Map(myCbind, df_list, colnames(df_new))

sapply(res, function(i) tail(colnames(i), 1))
# mtcars1 mtcars2 mtcars3 mtcars4 
#     "a"     "b"     "c"     "d" 

Upvotes: 1

Ricardo Semi&#227;o
Ricardo Semi&#227;o

Reputation: 4456

Does this work for you?

for(i in 1:4){
  df_list[[i]] = cbind(df_list[[i]], df_new[,i])}

Upvotes: 1

Related Questions