Saving elements of a list as data.frames using R

3.9k views Asked by At

How can I save each element of a list in a in a separate .RData file?

Consider the following example:

# Generating a list containing 3 matrices

set.seed(1)
mylist=list(M1=matrix(LETTERS[sample(1:26,9)],3),M2=matrix(LETTERS[sample(1:26,9)],3),M3=matrix(LETTERS[sample(1:26,9)],3))
mylist[1:2]

# $M1
# [,1] [,2] [,3]
# [1,] "G"  "U"  "W" 
# [2,] "J"  "E"  "M" 
# [3,] "N"  "S"  "L" 
# 
# $M2
# [,1] [,2] [,3]
# [1,] "B"  "P"  "J" 
# [2,] "F"  "I"  "N" 
# [3,] "E"  "Q"  "R" 

# Transforming the list of matrices into a list of data frames

mylistdf=lapply(mylist,function(x)as.data.frame(x))

My best try (does not work)

lapply(mylistdf,function(x)save(mylistdf[x],file=paste0(getwd(),names(mylistdf)[x],'.RData')))
4

There are 4 answers

0
akrun On BEST ANSWER

You can loop using names of the list object and save

lapply(names(mylistdf), function(x) {
       x1 <- mylistdf[[x]]
       save(x1, file=paste0(getwd(),'/', x, '.RData'))
  })
0
Christophe D. On

Have you tried something like :

save.image(get(paste0("mylistdf$M",X)),file=paste0(getwd(),names(mylistdf)[x],'.RData'))

into your lapply function ?

1
iembry On
invisible(lapply(names(mylist), function(u) {
assign(u, mylist[[u]])
save(list = u, file = paste0(getwd(), "/", u, ".RData"))
}))

The use of invisible comes from How to create automatic text file from a list in R? and the rest of the answer comes from loop through all files in a directory, read and save them in an object R.

I have tested the above code and it works.

0
MYaseen208 On

More efficient way is to use map function from purrr

library(purrr)
map(.x = names(mylistdf), .f = function(x){
  assign(x, mylistdf[[x]])
  save(list = x, file = paste0(x, ".RData"))
  }
  )

or

library(tidytable)
dt_map(.x = names(mylistdf), .f = function(x){
  assign(x, mylistdf[[x]])
  save(list = x, file = paste0(x, ".RData"))
  }
  )