0

I have 6-10 data frame objects I'd like to write out. Right now I have to manually write each one out with write.table. I'd like to simplify my code and loop through the objects and write them all out.

I've tried the suggestions here:

Write to files in R using a loop

writing many files in a for loop using R

However, I keep getting files that are correctly named but look like this:

> "x"  
"1" "listdata_cent"

Here is an example of my code:

names(lst) <- (ls(pattern = "^listdata"))
lst <- as.list((ls(pattern = "^listdata")))
for (i in nam) {
  write.table(i, file = paste(i, ".txt", sep = ""), col.names= TRUE, sep = "\t")
}

Any help you can give would be greatly appreciated. I'm sure I'm missing something simple.

Community
  • 1
  • 1
  • What is nam? it is not defined. – lmo Dec 20 '16 at 17:37
  • you should provide the data as well..., it is unclear on what you are applying pattern. – user5249203 Dec 20 '16 at 17:42
  • Looks like this could be related to this [question](http://stackoverflow.com/questions/4209512/write-list-of-data-frames-to-separate-csv-files-with-laply). – Nick Criswell Dec 20 '16 at 17:44
  • 1
    `i` is just the name. `get(i)` would find the object `i` – Richard Telford Dec 20 '16 at 17:47
  • 1
    Rather than having a bunch of data frames floating around, best practice would be to have a [list of data frames](http://stackoverflow.com/a/24376207/903061). The problem becomes trivial if your data frames are in a list. – Gregor Thomas Dec 20 '16 at 18:01
  • Sorry for the confusion Imo. "nam" was suppose to be "lst". Thanks to Nick, Richard, and Gregor! I was able to find an answer using all of your suggestions in combination. – betahelicies Dec 20 '16 at 22:17

1 Answers1

0

Thanks to Nick Criswell, Richard Telford, and Gregor. I was able to figure out a solution.

datalist = lapply(ls(pattern = "^listdata"), get)
names(datalist) <- (ls(pattern = "^listdata"))
for (i in 1:length(datalist)) {
  write.table(datalist[i], file = paste(names(datalist[i]), ".txt", sep = ""), col.names= TRUE, sep = "\t", quote=FALSE)
}

Looks like this could be related to this question. – Nick Criswell 4 hours ago 1
i is just the name. get(i) would find the object i – Richard Telford 4 hours ago 1
Rather than having a bunch of data frames floating around, best practice would be to have a list of data frames. The problem becomes trivial if your data frames are in a list. – Gregor 4 hours ago