Home > Blockchain >  How to add a column to every dataframe in a list of dataframes based on its name?
How to add a column to every dataframe in a list of dataframes based on its name?

Time:11-04

Let's say I have a list of dataframes df1_2018,df2_2018,df3_2018,...,dfn_2018

And I have another list of dataframes df1_2019,df2_2019,df3_2019,...,dfn_2019

I want to add a column called year to each dataframe with the value of year indicated in its dataframe name.

So, I want to run df1_2018$year <- 2018 but for all of the dataframes in the first list and df1_2019$year <- 2019 for all of the dataframes in the second list.

How can I do this concisely, perhaps with a for loop?

CodePudding user response:

Let's say two list as d_2018 and d_2019. Using lapply,

d_2018 <- lapply(d_2018, function(x){
  x$year <- 2018
  x
})

d_2019 <- lapply(d_2010, function(x){
  x$year <- 2019
  x
})

will helps

CodePudding user response:

Here is one way using purrr to add new column from the dataframe name.

library(purrr)

year_data <- list(data_2018, data_2019)

res <- map(year_data, function(x) 
        imap(x, function(data, name) {
        transform(data, year = sub('.*?_', '', name))
        }))
  • Related