Write many files in a for loop

Given your lst, the following will write this out to a series of TXT files with names equal to the name of lst, plus .txt:

lapply(names(lst),
       function(x, lst) write.table(lst[[x]], paste(x, ".txt", sep = ""),
                                    col.names=FALSE, row.names=FALSE, sep="\t", 
                                    quote=FALSE),
       lst)

To modify your for() loop, try:

for(i in seq_along(lst)) {
    write.table(lst[[i]], paste(names(lst)[i], ".txt", sep = ""), 
                col.names = FALSE, row.names = FALSE, sep = "\t", quote = FALSE)
}

The problem was trying to or assuming R would paste together the filenames for you.

Leave a Comment