向量化分配函数并在全局环境中创建对象

发布于 2025-01-17 14:14:19 字数 740 浏览 0 评论 0原文

我想对 assign 函数进行向量化,并创建一组反映提供的命名向量的参数,这些参数可在 .GlobalEnv 中直接使用。

代码

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

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

错误

点[[3L]][[1L]]中的错误:子集化的参数错误 环境

期望的结果

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

或通过分配

实际上,我想复制调用:

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

对于向量的每个元素并使用向量名称在.GlobalEnv中创建名称。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

娇纵 2025-01-24 14:14:19

此功能已经可以通过list2env

命名'列表x'中,创建一个“环境”,其中包含所有列表组件作为对象,或从“ x”中的“多分配”到预先存在的环境中。

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"

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"
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文