0

Using this option it is possible to read all csv of a specific path into one dataframe library(dplyr) library(stringr)

library(data.table) 

setwd("C:/Users/User/Desktop/myfile")
files <- list.files(path = "C:/Users/User/Desktop/myfile",pattern = ".csv")
temp <- lapply(files, fread, sep=",")
data <- rbindlist( temp )

What command could be the most appropriate in order to add a column which will have the file name for every row?

zx8754
  • 52,746
  • 12
  • 114
  • 209
Erik Bodg
  • 302
  • 2
  • 10

2 Answers2

3

You can use sapply to read all the files in a list and with rbindlist combine them into one dataframe with a new column filename which has name of the file in every row.

library(data.table)
result <- rbindlist(sapply(files, fread,simplify = FALSE), idcol = 'filename')
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
1

You want to add a column to each data.frame, with the file name?

How about doing it before rbindlist?

temp <- lapply(files,fread,sep=",")
temp <- for(i in seq_along(temp)) temp[[i]] = cbind(File=files[i],temp[[i]])
data <- rbindlist( temp )
Joezerz
  • 129
  • 6