2

I have a large list of 4951 named elements. Each of these elements are basically letters (that is, they are string characters). What I would like to do is to export each of the elements of the list as a separate text file, with the name of the file corresponding to its name on the list.

A simple version of what I have is this:

 letter1 <- c("here is some text")
 letter2 <- c("and here is some more text")
 letter3 <- c("and this is the final one")

 list <- list(letter1 = letter1, letter2 = letter2, letter3 = letter3)

And I would like to have the following:

letter1.txt, the contents of which are "here is some text"
letter2.txt, the contents of which are "and here is some more text"
letter3.txt, the contents of which are "and this is the final one"

I imagine that I should use a loop. However, I don't know how to get beyond this:

for (i in 1:length(list)){

}
JoeF
  • 733
  • 1
  • 7
  • 21

2 Answers2

6

for (i in 1:length(list)) { write.csv(list[i], file=paste0(names(list)[i], ".txt")) }

Edit

If you need the output directory in the function:

 write.csv(list[i], file=paste0("output/", names(list)[i], ".txt"))
Pierre L
  • 28,203
  • 6
  • 47
  • 69
3

Try this:

filenames <- names(list)
for (i in 1:length(list)){
  outname <- paste("c:/testFolder/", filenames[i], ".txt", sep= "")
  write.table(list[[i]], outname, col.names= F, row.names= F, quote= F)
}
Hans Roelofsen
  • 741
  • 1
  • 7
  • 13