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
.
是三个单独的对象a,b和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
.
但它失败了,名字中出现错误(x)[1] << - x [1]:未找到对象'x'。
How might I achieve my aim?
我怎样才能实现目标?
3 个解决方案
#1
29
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
P. S.这是我的评论作为答案
#2
4
This also would work:
这也可行:
lapply(seq_along(obj), function(i) assign(names(obj)[i], obj[[i]], envir = .GlobalEnv))
#3
0
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
#1
29
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
P. S.这是我的评论作为答案
#2
4
This also would work:
这也可行:
lapply(seq_along(obj), function(i) assign(names(obj)[i], obj[[i]], envir = .GlobalEnv))
#3
0
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