Reputation: 4686
Let's say I have a nested list in R. How can I save
the list into .Rdata
as individual top level elements of the list ?
What I mean is, e.g. sample data
samplist <- list(a=list(x=2, y=runif(10)),
b=list(x=3, y=rbinom(10, 5, .5)),
c=list(x=0, y=rnorm(10))
)
The output I want is the equivalent of
a <- samplist$a
b <- samplist$b
c <- samplist$c
save(a, b, c, file=output.Rdata)
done automatically across a list with many top-level elements. I tried unlist
with recursive=F
but that flattened the lists in the nested list. How can I do it instead?
Upvotes: 2
Views: 885
Reputation: 5536
The solution by converting list as an environment.
# Test list
samplist <- list(a=list(x=2, y=runif(10)),
b=list(x=3, y=rbinom(10, 5, .5)),
c=list(x=0, y=rnorm(10)))
# Convert list as an environment
env <- as.environment(samplist)
# Save objects form the environment
save(list = ls(env), file = "output.Rdata", envir = env)
# Load file
load("output.Rdata")
Upvotes: 1
Reputation: 132706
You don't need to store the environment:
do.call(save,
c(as.list(names(samplist)),
list(file = "output.Rdata",
envir = as.environment(samplist))))
load("output.Rdata")
print(a)
#$x
#[1] 2
#
#$y
#[1] 0.6815263 0.5448165 0.3346296 0.2127811 0.1804896 0.8416717 0.1060889 0.5679649 0.6392396 0.9770226
Upvotes: 3