rloopsfor-loopread.tablewrite.table

Write tables from R using for loop, where table names contain the index of the loop


I have many .csv files in a folder, which are read with the following command:

for(i in 1:length(files)) {
assign(paste("tbl",i,sep=""),fread(file=files[i],skip=1,dec=",",sep="\t")) }

So I read every .csv file into different table, with the name tbl1, tbl2, tbl3... I would like to write these tables into one file with the following for loop:

write.table(tbl1,file="data.csv", append=F, sep="\t", dec=",",col.names=T)

for (i in 2:length(files)) {
     val <- paste0("tbl",i)
     write.table(val, file="data.csv", append=T, sep="\t", dec=",", col.names=F)
}

But only paste "tbl2", "tbl3"... into the data.csv file instead of the data from tables.


Solution

  • paste0 returns character as output, hence it's printing the tbl2,tbl3,.. you need to convert it into object, which can be done using get. If you want to use same format of code:

    write.table(tbl1,file="data.csv", append=F, sep="\t", dec=",",col.names=T)
    
    for (i in 2:length(files)) {
         val <- get(paste0("tbl",i))
         write.table(val, file="data.csv", append=T, sep="\t", dec=",", col.names=F)
    }