How to save the elements of a list individually in R?

痴心易碎 提交于 2019-12-11 06:43:48

问题


So I've got a pretty long list of elements, and I want to save each of these elements individually as a dataframe. Right, now I'm trying to do so by:

for (i in 1:length(mylist)) {
  save.dta13(mylist[i], file=paste0(names(mylist)[i], ".dta"))
}

But that doesn't seem to be working, any ideas?


回答1:


We can use lapply to loop over the names of the list

lapply(names(mylist), function(nm)
     save.dta13(mylist[[nm]], paste0(nm, ".dta")))



回答2:


Here is another solution (slightly different from what akrun has posted )

#An example list

L=list(mat1=matrix(c(1,2,3,4,5,6,7,8,9),3,3),mat2=matrix(c(1,2,3,4,5,6,7,8,9),3,3),mat3=matrix(c(1,2,3,4,5,6,7,8,9),3,3))

#Convert elements of list to a data frame
L_DF = lapply(L,function(x)as.data.frame(x))

#Check the class of each element 
 class(L_DF$mat1)
#[1] "data.frame"



  class(L_DF$mat2)
#[1] "data.frame"


     class(L_DF$mat3)
#[1] "data.frame"


   names(L_DF)
#[1] "mat1" "mat2" "mat3"



#Save as dta

lapply(names(L_DF), function(x) {
     f <- L_DF[[x]]
     save(f, file=paste0(getwd(),'/', x, '.dta'))
 })


来源:https://stackoverflow.com/questions/38310741/how-to-save-the-elements-of-a-list-individually-in-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!