gpt4 book ai didi

r - 从 R 中的列表打包和解包元素

转载 作者:行者123 更新时间:2023-12-04 12:21:17 25 4
gpt4 key购买 nike

我有两个与在 R 中使用 list 相关的问题,我想看看如何改进我的天真解决方案。我在 similar topic 上看到了问题在这里,但那里描述的方法没有帮助。

问题 1:

MWE:

a  <- c(1:5)
b <- "adf"
c <- array(rnorm(9), dim = c(3,3) )
  • 制作一个列表,名称为“packedList”,同时保留名称
    所有变量。
  • 当前解决方案:packedList <- list(a = a, b = b, c = c)

  • 但是,如果变量的数量(上述问题中的三个,即 a, b, c )是
    大(假设我们有 20 个变量),那么我当前的解决方案可能不是
    最好的。

    这个想法在返回大量变量时很有用
    一个函数。

    问题 2:

    MWE:给定 packedList , 提取变量 a, b, c
  • 我想将给定列表(即packedList)中的所有元素提取到环境中,同时保留它们的名称。这是任务 1 的反向操作。

  • 例如:给定环境中的变量packedList,我可以如下定义a、b和c:
     a <- packedList$a
    b <- packedList$b
    c <- packedList$c

    但是,如果变量的数量非常大,那么我的解决方案可能会很麻烦。
    - 经过一些谷歌搜索,我找到了 one solution但我不确定这是否是最优雅的解决方案。解决方法如下图:
     x <- packedList
    for(i in 1:length(x)){
    tempobj <- x[[i]]
    eval(parse(text=paste(names(x)[[i]],"= tempobj")))
    }

    最佳答案

    您最有可能正在寻找 mget (Q1) 和 list2env (Q2)。

    这是一个小例子:

    ls()  ## Starting with an empty workspace
    # character(0)

    ## Create a few objects
    a <- c(1:5)
    b <- "adf"
    c <- array(rnorm(9), dim = c(3,3))

    ls() ## Three objects in your workspace
    [1] "a" "b" "c"

    ## Pack them all into a list
    mylist <- mget(ls())
    mylist
    # $a
    # [1] 1 2 3 4 5
    #
    # $b
    # [1] "adf"
    #
    # $c
    # [,1] [,2] [,3]
    # [1,] 0.70647167 1.8662505 1.7941111
    # [2,] -1.09570748 0.9505585 1.5194187
    # [3,] -0.05225881 -1.4765127 -0.6091142

    ## Remove the original objects, keeping just the packed list
    rm(a, b, c)

    ls() ## only one object is there now
    # [1] "mylist"

    ## Use `list2env` to recreate the objects
    list2env(mylist, .GlobalEnv)
    # <environment: R_GlobalEnv>
    ls() ## The list and the other objects...
    # [1] "a" "b" "c" "mylist"

    关于r - 从 R 中的列表打包和解包元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30283389/

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