gpt4 book ai didi

r - 向量化赋值函数并在全局环境中创建对象

转载 作者:行者123 更新时间:2023-12-04 11:01:33 24 4
gpt4 key购买 nike

我想对 assign 函数进行矢量化,并创建一组反射(reflect)提供的命名矢量的参数,这些参数将直接在 .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(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"

关于r - 向量化赋值函数并在全局环境中创建对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50646629/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com