0

So i have a list of 20 data frames. Each data frame represents a year (1980-2000), id like to merge all my data frames into one but have a column representing the year of each data frame so i can continue to manipulate by time. All data frames have the same column names in the list. So merging should not be hard but i need to identify each data frame.

Example:
list of data frames
df1  <- Name2000
df2  <- Name1999
.
.
.
df20 <- Name1980

What im looking for

TotalDF:

x1 x2 x3 new_var
x  x  x  2000
x  x  x  2000
x  x  x  1999
x  x  x  1999
.  .  .  . 
.  .  .  . 
x  x  x  1980

I got my list of dataframes doing this:

filenames <- list.files(path="C:/Users/clint/Documents/R/Personal 
work/Fires/rain/", full.names=TRUE)

All <- lapply(filenames,function(i){
  i <- paste("",i,sep="")
  read.csv(i, header=FALSE)
})
filenames <- gsub("-",".",filenames)
names(All) <- gsub(".csv","",filenames)
Clinton Woods
  • 249
  • 1
  • 2
  • 11
  • 2
    `All <- lapply(filenames,function(i){ i <- paste("",i,sep="") df <- read.csv(i, header=FALSE) df$new_var <- gsub("-|.csv",".",i) df }); do.call(rbind, All)`. – Abdou Oct 29 '17 at 17:57
  • 2
    @Abdou, pls try to remember to add semi-colons when you post multi-line code in comments. – r2evans Oct 29 '17 at 18:03
  • Well that solved the problem. thank you very much for the fast fix. – Clinton Woods Oct 29 '17 at 18:05
  • @r2evans, thanks for the tip. The inner semi-colons are tough to keep up with. – Abdou Oct 29 '17 at 18:10
  • Other possible duplicates: https://stackoverflow.com/a/42822251/3817004, https://stackoverflow.com/a/38857332/3817004 – Uwe Oct 30 '17 at 00:10

1 Answers1

2

For additional reference,

dplyr::bind_rows([list], .id='year')

is probably the easiest way assuming you've named the list elements by year already.

Jul
  • 1,129
  • 6
  • 12