1

Having this code it is possible to read multiple csv from a file path

setwd("C:/Users/Nathalie/mycsvs")
files <- list.files(path = "C:/Users/Nathalie/mycsvs",pattern = ".csv")
temp <- lapply(files, fread, sep=",")

How is it possible to add a column to the dataframe which will have the file name each row came from?

Nathalie
  • 1,228
  • 7
  • 20
  • Does this answer your question? [Add "filename" column to table as multiple files are read and bound](https://stackoverflow.com/questions/46299777/add-filename-column-to-table-as-multiple-files-are-read-and-bound) – camille Jan 23 '20 at 13:48

1 Answers1

4

We can use Map and create a new column with cbind to show filename for each file.

Map(cbind, lapply(files, data.table::fread, sep=","), filename = files)

We can also use functions from purrr package to do the same.

library(purrr)
map2(map(files, data.table::fread, sep=","), files, cbind)

To use lapply, we can loop over the index of filenames instead and use transform to add new column with name of the file.

lapply(seq_along(files), function(x) transform(read.csv(files[x]), file = files[x]))
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213