我有一个列表,并想打破列表的元素融入到单独的物体在地球环境。
例如,我想名单:
obj <- list(a=1:5, b=2:10, c=-5:5)
是三个单独对象a
, b
,和c
。
我试图实现这一目标:
lapply(obj, FUN = function(x) names(x)[1] <<- x[1])
但它失败了,用Error in names(x)[1] <<- x[1] : object 'x' not found
。
我怎么可能会实现我的目标是什么?
有映射列表环境特殊功能:
> 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"
PS它是作为一个答案提供我的意见
这也将工作:
lapply(seq_along(obj), function(i) assign(names(obj)[i], obj[[i]], envir = .GlobalEnv))
我不建议这样做,但你可以使用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