使用 R 将列表元素保存为 data.frames

Saving elements of a list as data.frames using R

如何将列表的每个元素保存在单独的 .RData 文件中?

考虑以下示例:

# 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))

我尽力了(没用)

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

你有没有尝试过类似的东西:

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

进入您的 lapply 函数 ?

您可以使用列表对象的 namessave

循环
lapply(names(mylistdf), function(x) {
       x1 <- mylistdf[[x]]
       save(x1, file=paste0(getwd(),'/', x, '.RData'))
  })
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? and the rest of the answer comes from loop through all files in a directory, read and save them in an object R

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

更有效的方法是使用 purrr

中的 map 函数
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"))
  }
  )