Vectorize the assign function and create objects in global environment

后端 未结 1 391
囚心锁ツ
囚心锁ツ 2020-12-21 13:49

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 .Glob

相关标签:
1条回答
  • 2020-12-21 14:29

    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"
    
    0 讨论(0)
提交回复
热议问题