I am looping through multiple files where each file creates a table. I would like to save each table to a file so that I have all of the tables together. The idea is that after each file runs, the final output will append to the previous final output in a table. My current code loops through each file but only takes the data from the last file in the folder and repeatedly appends to the same output. Here is my code:
filenames <- Sys.glob("*.xlsx")
print(filenames)
final.df<-data.table()
for(i in 1:length(filenames)) {
#... final table named "Stats"
Stats$file <- i #To view which file is listed
df <- data.table(Stats)
final.df <- rbind(final.df, df)
drop(df)
}
When I run the code, the file names are printed 26 times in this format:
[1] "file1.xlsx" "file2.xlsx"
[1] "file1.xlsx" "file2.xlsx"
[1] "file1.xlsx" "file2.xlsx"
...
My current output prints in this format:
X Y Z File
1 10 2 file2
2 6 2 file2
1 9 2 file2
1 10 2 file2
2 6 2 file2
1 9 2 file2
My desired output would look like the following:
X Y Z File
0 4 1 file1
1 7 1 file1
0 1 1 file1
1 10 2 file2
2 6 2 file2
1 9 2 file2
SOLUTION
files <- list.files(pattern = "\\.xlsx$")
print(files)
final.df<-list()
for(title in c(paste(files, sep="."))) {
#... (Some data named Stats)
Stats<-data.table(Stats)
final.df[[title]] <- Stats
print(final.df)
}
Final <- rbindlist(final.df)