Vectorize the assign function and create objects in global environment

ぃ、小莉子 提交于 2019-11-28 10:07:20

问题


I would like to vectorize the assign function and create a set of arguments reflecting provided named vector that would be directly available in the .GlobalEnv.

Code

vec_args <- c(arg1 = 1,
              arg2 = 2,
              arg3 =  3)

Vectorize(assign)(x = names(vec_args),
                  value = vec_args,
                  envir = globalenv())

Error

Error in dots[[3L]][[1L]] : wrong arguments for subsetting an environment

Desired results

ag1 <- 1; arg2 <- 2; arg3 <- 3; ls()
# [1] "ag1"        "arg2"       "arg3"       "vec_args"

or via assign:

In effect, I would like to replicate the call:

assign(x = "arg1", value = vec_args[1], envir = globalenv())

for each element of a vector and use vector names to create names in .GlobalEnv.


回答1:


This functionality is already available via list2env:

From a named ‘list x’, create an ‘environment’ containing all list components as objects, or “multi-assign” from ‘x’ into a pre-existing environment.

list2env(as.list(vec_args), envir = globalenv())
ls()
# [1] "arg1"     "arg2"     "arg3"     "vec_args"

Something like the following would also work:

rm(list = ls())
vassign <- Vectorize(assign, c("x", "value"))
vec_args <- c(arg1 = 1, arg2 = 2, arg3 = 3)
vassign(names(vec_args), vec_args, envir = globalenv())
ls()
# [1] "arg1"     "arg2"     "arg3"     "vassign"  "vec_args"


来源:https://stackoverflow.com/questions/50646629/vectorize-the-assign-function-and-create-objects-in-global-environment

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!