I have a list of dataframes:
lists <- replicate(10, as.data.frame(matrix(rnorm(100), 10, 10)), simplify = FALSE)
names(lists) <- LETTERS[1:10]
I want to write all dataframes to a separate file named according to their object name in R. I tried lapply
with paste
, but this horribly failed:
lapply(lists, function(x) write.table(x, file=paste(x,".txt"), sep="\t"))
Error in file(file, ifelse(append, "a", "w")) :
invalid 'description' argument
In addition: Warning message:
In if (file == "") file <- stdout() else if (is.character(file)) { :
the condition has length > 1 and only the first element will be used
Called from: file(file, ifelse(append, "a", "w"))
How to do this without writing n single lines for n data.frames?
Creating a list of Dataframes. To create a list of Dataframes we use the list() function in R and then pass each of the data frame you have created as arguments to the function.
Data frame columns can contain lists You can also create a data frame having a list as a column using the data. frame function, but with a little tweak. The list column has to be wrapped inside the function I.
You are looping over the list elements, and not the names of the list elements. So the expression paste(x,".txt")
tries to paste a data.frame
to .txt
, but you want to paste the name of the list element to .txt
. So you can try the following:
lists <- replicate(10, as.data.frame(matrix(rnorm(100), 10, 10)), simplify = FALSE)
names(lists) <- LETTERS[1:10]
lapply(names(lists), function(x) write.table(lists[[x]], file=paste(x,".txt"), sep="\t"))
To suppress the console output, wrap the statement in invisible()
, or alternatively use a regular for-loop:
for (x in names(lists))
write.table(lists[[x]], file=paste(x,".txt"), sep="\t")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With