向量化赋值函数并在全局环境中创建对象
Vectorize the assign function and create objects in global environment
我想对 assign
函数进行矢量化,并创建一组反映提供的命名向量的参数,这些参数可直接在 .GlobalEnv
.
中使用
代码
vec_args <- c(arg1 = 1,
arg2 = 2,
arg3 = 3)
Vectorize(assign)(x = names(vec_args),
value = vec_args,
envir = globalenv())
错误
Error in dots[[3L]][[1L]] : wrong arguments for subsetting an
environment
想要的结果
ag1 <- 1; arg2 <- 2; arg3 <- 3; ls()
# [1] "ag1" "arg2" "arg3" "vec_args"
或通过assign
:
实际上,我想复制调用:
assign(x = "arg1", value = vec_args[1], envir = globalenv())
对于向量的每个元素,并使用向量名称在 .GlobalEnv
中创建名称。
此功能已通过 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"
像下面这样的东西也可以工作:
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"
我想对 assign
函数进行矢量化,并创建一组反映提供的命名向量的参数,这些参数可直接在 .GlobalEnv
.
代码
vec_args <- c(arg1 = 1,
arg2 = 2,
arg3 = 3)
Vectorize(assign)(x = names(vec_args),
value = vec_args,
envir = globalenv())
错误
Error in dots[[3L]][[1L]] : wrong arguments for subsetting an environment
想要的结果
ag1 <- 1; arg2 <- 2; arg3 <- 3; ls()
# [1] "ag1" "arg2" "arg3" "vec_args"
或通过assign
:
实际上,我想复制调用:
assign(x = "arg1", value = vec_args[1], envir = globalenv())
对于向量的每个元素,并使用向量名称在 .GlobalEnv
中创建名称。
此功能已通过 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"
像下面这样的东西也可以工作:
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"