51

I have a list, and would like to break the elements of the list into seperate objects in the global environment.

For example, I would like the list:

obj <- list(a=1:5, b=2:10, c=-5:5)

to be three seperate objects a, b, and c.

I tried to achieve this with:

lapply(obj, FUN = function(x) names(x)[1] <<- x[1])

But it failed, with Error in names(x)[1] <<- x[1] : object 'x' not found.

How might I achieve my aim?

Jaap
  • 81,064
  • 34
  • 182
  • 193
ricardo
  • 8,195
  • 7
  • 47
  • 69

4 Answers4

72

There is special function for mapping list to environment:

> obj <- list(a=1:5, b=2:10, c=-5:5)
> ls()
[1] "obj"
> list2env(obj,globalenv())
<environment: R_GlobalEnv>
> ls()
[1] "a"   "b"   "c"   "obj"

P. S. It is my comment provided as an answer

Gregory Demin
  • 4,596
  • 2
  • 20
  • 20
10

This also would work:

lapply(seq_along(obj), function(i) assign(names(obj)[i], obj[[i]], envir = .GlobalEnv))
Tyler Rinker
  • 108,132
  • 65
  • 322
  • 519
1

In case the list isn't yet a named list, we need to set names first, e.g. with incrementing letters.

obj2 <- list(1:5, 2:10, -5:5)

list2env(setNames(obj2, letters[seq(obj2)]), envir=.GlobalEnv)
ls()
# [1] "a"    "b"    "c"    "obj2"
jay.sf
  • 60,139
  • 8
  • 53
  • 110
-1

I don't recommend it but you could use attach

> obj <- list(a=1:5, b=2:10, c=-5:5)
> attach(obj)
> a
[1] 1 2 3 4 5
> b
[1]  2  3  4  5  6  7  8  9 10
> c
 [1] -5 -4 -3 -2 -1  0  1  2  3  4  5
Dason
  • 60,663
  • 9
  • 131
  • 148
  • 1
    This does not what OP asked, it just attaches the object `obj` to the search path. That doesn't mean you assign the elements of the list to independent objects in the global environment. Gregory has the correct answer. – Joris Meys Dec 10 '12 at 12:35
  • @JorisMeys Sure but they never really said why they wanted to do this either. `attach` allows you to pretend like they're a part of the global environment (at least in simple cases) with very little work. With that said I definitely think Gregory's answer is the best out of the answers given. – Dason Dec 10 '12 at 14:49
  • I see why you mentioned it, but the use of `attach` poses a lot more problems than it solves, not in the least when you try to change one of the elements in the list. As said in the [R Style Guide](http://google-styleguide.googlecode.com/svn/trunk/google-r-style.html#attach) : The possibilities for creating errors when using attach are numerous. Avoid it. – Joris Meys Dec 10 '12 at 15:07
  • @JorisMeys I agree. Which is why I don't recommend it. I also don't really like the whole idea posted in the question though. There are also dangers associated with Gregory's answer as well too – Dason Dec 10 '12 at 15:57