3

I'm using mapply() to save elements from a list in separate files. E.g.

file.names <- c('~/a.RData', '~/b.RData')
data.list <- list(foo = c(1:10), bar = rep(1, 10))

mapply(function(x, y) save(x, file = y), data.list, file.names)

and I'd like to be able to call the elements by their original name after loading them again. Now I get

load('~/a.RData')
ls()
"x"

but I'd like to get

load('~/a.RData')
ls()
"foo"
Lukas
  • 655
  • 8
  • 20

2 Answers2

5

Good question, and this is probably not the ideal answer. Anyway, one possibility is to use the list as an environment and couple that with the list argument in save(). The key here is to get the ordering right, as ls() orders its output. with() creates an environment from the list, so we can use the list argument easily.

with(data.list, {
    mapply(
        function(x, y) save(list = x, file = y),
        ls()[order(names(data.list))], 
        file.names
    )
})
# $foo
# NULL
#
# $bar
# NULL

Check:

load('~/a.RData')
ls()
# [1] "data.list"  "f"          "file.names" "foo"       
load('~/b.RData')
ls()
# [1] "bar"        "data.list"  "f"          "file.names" "foo"     
foo
# [1]  1  2  3  4  5  6  7  8  9 10
bar
# [1] 1 1 1 1 1 1 1 1 1 1
Rich Scriven
  • 97,041
  • 11
  • 181
  • 245
4

Here is my try:

mapply(function(x, y, z) {
  assign(y,x)
  save(list=y,file=z)
}, data.list, names(data.list), file.names)

Let's check the output:

#rm(list=ls())
load('~/a.RData')
ls()
#[1] "foo"

load('~/b.RData')
ls()
[1] "bar" "foo"

foo
#[1]  1  2  3  4  5  6  7  8  9 10
bar
#[1] 1 1 1 1 1 1 1 1 1 1
cryo111
  • 4,444
  • 1
  • 15
  • 37