0

I have 18 data set from 2002-2020 that I want to add a year column to before I bind them all together. I created this function:

year_add <- function(x,y) {mutate(x, Year =y)} ## adds the year variable to data frame

which works perfectly for one data frame, but I don't know how to run it through a list of all 18 data sets. I have tried for loops and lapply, but can't seem to get any of them to work... Any suggestions?

FYI, to run the code on one data set, I simply put: year_add(data2002, "2002")

Khann
  • 13
  • 3
  • Try to make this a [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example). You tried loops and lapply how? – camille Feb 04 '20 at 15:03
  • Hard to answer without reprodicible example,did you look into map (from the purrr) package. – Annet Feb 04 '20 at 15:12

1 Answers1

0

Try

names(list_of_dataframes) <- 2002:2020
dplyr::bind_rows(list_of_dataframes, .id = "Year")
robertdj
  • 909
  • 1
  • 5
  • 10