R中列表中的元素的打包和解包 [英] Packing and unpacking elements from list in R

查看:74
本文介绍了R中列表中的元素的打包和解包的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个与在R中使用list有关的问题,我试图查看如何改善天真的解决方案.我在这里看到了关于类似主题的问题,但是所描述的方法没有帮助.

I have two questions related to using list in R and I am trying to see how I can improve my naive solution. I have seen questions on similar topic here but the approach described there is not helping.

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个变量),那么我当前的解决方案可能不是最好的.

    However, if the number of variables (three in above problem i.e. a, b, c) is large (say we have 20 variables), then my current solution may not be the best.

    这个想法在返回大量变量时很有用一个功能.

    This is idea is useful while returning large number of variables from a function.

    MWE:给定 packedList ,提取变量a,b,c

    MWE: Given packedList, extract variables a, b, c

    • 我想将给定列表(即packedList)中的所有元素提取到环境中,同时保留它们的名称.这与任务1相反.

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

    For example: Given variable packedList in the environment, I can define a, b, and c as follows:

     a <- packedList$a
     b <- packedList$b
     c <- packedList$c
    

    但是,如果变量的数量很大,那么我的解决方案可能很麻烦.-在Google搜索后,我发现了一个解决方案,但我我不确定这是否是最优雅的解决方案.解决方案如下所示:

    However, if the number of variables is very large then my solution can be cumbersome. - After some Google search, I found one solution but I am not sure if it is the most elegant solution either. The solution is shown below:

     x <- packedList
     for(i in 1:length(x)){
           tempobj <- x[[i]]
           eval(parse(text=paste(names(x)[[i]],"= tempobj")))
     }
    

    推荐答案

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

    You are most likely looking for mget (Q1) and 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中列表中的元素的打包和解包的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆