Reputation: 247
If I have list element containing multiple data frames, and I want to write them as individual text files on my disk by names NP1 , NP2, NP3, how can I do that?
I used the following,
lapply(lst1,write.table)
But this doesn't solve the issue. How can I do it? Thanks!
Upvotes: 2
Views: 730
Reputation: 99331
Here are two ways. One with a for
loop and one with mapply
Set up a list of data frames:
lst1 <- list(data.frame(x = 1:5, y = letters[1:5]),
data.frame(z = 6:10, w = LETTERS[1:5]))
Loop through the list with a for
loop:
for(i in seq_along(lst1)) {
write.table(lst1[[i]], paste0("NP", i, ".txt"))
}
Check the result:
read.table("NP1.txt")
read.table("NP2.txt")
Using mapply
:
nm <- paste0("NP", seq_along(lst1), ".txt") ## create the file names
mapply(write.table, lst1, file = nm) ## write the files
# [[1]]
# NULL
#
# [[2]]
# NULL
Note that if you don't want the NULL
values that come as a printed result, you can wrap the call in invisible
invisible(mapply(write.table, lst1, file = nm))
Upvotes: 2