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.

6
  • What is nam? it is not defined. Commented Dec 20, 2016 at 17:37
  • you should provide the data as well..., it is unclear on what you are applying pattern. Commented Dec 20, 2016 at 17:42
  • Looks like this could be related to this question. Commented Dec 20, 2016 at 17:44
  • 1
    i is just the name. get(i) would find the object i Commented Dec 20, 2016 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. The problem becomes trivial if your data frames are in a list. Commented Dec 20, 2016 at 18:01

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.