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.
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.