【问题标题】:Return list of lists from foreach loop in R从R中的foreach循环返回列表列表
【发布时间】:2019-05-08 05:46:32
【问题描述】:

我有一个函数,它返回两个对象的列表(一个列表l 和一个数字n)。我想在foreach 循环中循环这个函数。

create_lists <- function(){
l = sample(100, 5)
n = sample(100, 1)
return(list(l=l, n=n))}

因为create_lists 有一个列表作为输出,this post 告诉我使用如下所示的组合函数:

combine_custom <- function(list1, list2){
  ls = c(list1$l, list2$l)
  ns = c(list1$n, list2$n)
  return(list(l = ls, n = ns))
}

所以现在我的foreach 循环看起来像这样:

m = foreach(i=1:5, .combine = combine_custom)%do%{
   create_lists()}

我想要的输出是:

m$l
[[1]]
[1] 100  25  86  21  28

[[2]]
[1] 78 37 79 41 61

[[3]]
[1] 73 22 78 94 13

[[4]]
[1] 15 28 76 78 52

[[5]]
[1] 32 93 92  2  1

m$n
[1] 52 56 3 79 82

但我得到的是这样的:

$l
 [1] 84 28 75 59 68 84 28 75 59 68

$n
[1] 31 91 18 98 39

所以我有两个问题: 1) 为什么除了两个l 列表之外的所有内容都被删除了? 2) 如何使m$l 成为列表列表?

编辑: 我尝试了从here 得到的另一种方法,它不使用c

combine_custom <- function(list1, list2){
      ls = list1$l[[length(list1$l)+1]] = list(list2$l)
      ns = c(list1$n, list2$n)
      return(list(l = ls, n = ns))
    }

但这给出了与上述相同的结果,确切地说:

$l
$l[[1]]
[1] 65 84 48 81 82


$n
[1] 88 79 92 36 71

【问题讨论】:

  • combine_custom 中,你的意思是 ``` ls = c(list1$l, list2$l)``` 而不是将 list2 与自身结合起来吗?那应该解决问题(1)。问题(2)是因为使用c 来组合列表。
  • 是的,谢谢,这解决了一个问题。但我仍然坚持列表列表。你会用什么代替?我试过link这个,但结果相同。

标签: r list foreach


【解决方案1】:

我找到了另一种避免上述问题的方法,即combine 必须先创建一个新列表,然后再添加列表。 此外,我使用的实际函数实际上返回一个列表列表,因此以下证明很有用:

combine_custom <- function(list1, list2) {
     if (plotrix::listDepth(list1$l) > plotrix::listDepth(list2$l)) {
        ls  <- c(list1$l, list(list2$l))
    } else {
        ls <- c(list(list1$l), list(list2$l))
     }
     ns <- c(list1$n, list2$n)
     return(list(l = ls, n = ns))
}

如果函数可以返回不同嵌套深度的列表,这并不完美,但它适用于我的情况。

【讨论】:

    【解决方案2】:

    combine 部分很麻烦,因为在第一次迭代时,它需要从两个列表中创建一个列表,但在第二次迭代时,它需要将一个列表作为元素附加到列表中列表。

    另一种方法(可能有效也可能无效,具体取决于您的实际数据/问题的大小)是使用 purrr 包来处理列表:

    > m <- foreach(i=1:3)%do%{create_lists()}
    > m
    [[1]]
    [[1]]$l
    [1] 21 33 12 50 36
    
    [[1]]$n
    [1] 74
    
    
    [[2]]
    [[2]]$l
    [1] 12 80 39 78  6
    
    [[2]]$n
    [1] 74
    
    
    [[3]]
    [[3]]$l
    [1]  9 61 75 63 94
    
    [[3]]$n
    [1] 2
    
    
    > purrr::transpose(m)
    $l
    $l[[1]]
    [1] 21 33 12 50 36
    
    $l[[2]]
    [1] 12 80 39 78  6
    
    $l[[3]]
    [1]  9 61 75 63 94
    
    
    $n
    $n[[1]]
    [1] 74
    
    $n[[2]]
    [1] 74
    
    $n[[3]]
    [1] 2
    

    希望有帮助!

    【讨论】:

      猜你喜欢
      • 2020-02-28
      • 2019-03-24
      • 1970-01-01
      • 1970-01-01
      • 2021-12-17
      • 2018-07-12
      • 2020-07-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多