Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

r - Vectorize the assign function and create objects in global environment

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...