问题
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