Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

writing a list of dataframes to file with lapply: How to paste object names to file names?

Tags:

list

r

lapply

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?

like image 257
nouse Avatar asked Feb 11 '18 17:02

nouse


People also ask

Can you put Dataframes in a list?

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.

Can I store Dataframe in list R?

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.


1 Answers

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")
like image 137
Florian Avatar answered Sep 23 '22 13:09

Florian