Saving elements of a list as data.frames using R

时间:2015-06-15 14:42:53

标签: r list save lapply

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 个答案:

答案 0 :(得分:2)

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'))
  })

答案 1 :(得分:1)

Have you tried something like :

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

into your lapply function ?

答案 2 :(得分:1)

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

使用invisible来自How to create automatic text file from a list in R?,其余答案来自loop through all files in a directory, read and save them in an object R

我已经测试了上面的代码并且有效。

答案 3 :(得分:0)

更有效的方法是使用map中的purrr函数

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

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