0

I'm trying to read multiple csv files in a folder that have the same structure & I found this question where zx8754 solved it just like I needed, but I realized that I gotta keep and id on each table to end up with something like below file

abc <- structure(c("1", "1", "1", "2", "2", "2", "3", "3", "3", "a", 
"a", "a", "b", "b", "b", "c", "c", "c", "a", "a", "a", "b", "b", 
"b", "c", "c", "c", "a", "a", "a", "b", "b", "b", "c", "c", "c"
), .Dim = c(9L, 4L))

Could I gently get some guidance for turning below code in something that adds id column for each csv in the folder?

myMergedData <- 
  do.call(rbind,
          lapply(list.files(path = "N:/Ring data by cruise"), read.csv))

Thanks in advance!

MelaniaCB
  • 427
  • 5
  • 16

1 Answers1

1

You can create an id column using map_df.

myMergedData <- purrr::map_df(list.files(path = "N:/Ring data by cruise"), 
                              read.csv, .id = 'id')

If you want to do this in base R :

data <- lapply(list.files(path = "N:/Ring data by cruise"), read.csv)
myMergedData <- Map(cbind, data, id = seq_along(data))
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213