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')))
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'))
})
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With