I have several excels with the same structure:
COL1 COL2
1 2
3 4
5 6
I read the data:
lista1 <- list.files(pattern = "*.xls")
df_list <- lapply(lista1,
FUN = function(files) {
read.table(files, header = TRUE, sep = "") })
I unify all the files in a df:
library(data.table)
tabla <- rbindlist(df_list)
Which would leave me something like this:
COL1 COL2
1 2
3 4
5 6
7 8
9 10
11 12
I want to add, I don't care as another column or as a row name, the name of the file where the data was
COL1 COL2 COL3
1 2 fichero1.xls
3 4 fichero1.xls
5 6 fichero1.xls
7 8 fichero2.xls
9 10 fichero2.xls
11 12 fichero2.xls
I have tried with loops replicating the name 3 times but I can't hit the key.
df$col3[j]<-rep(i,3)
You can make it the argument
idcol =
of the same functionrbindlist
you are using.Make sure that the list
df_list
is a named list and that the names of each element are the name of the file.When you bind to the data.frame use
idcol = "COL3"
. I can't verify it as I don't have the files, but it should work.