Reputation: 1238
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?
Upvotes: 1
Views: 3245
Reputation: 389325
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]))
Upvotes: 4