首页 > 解决方案 > 在R中的另一个列表中迭代一个列表

问题描述

我有一个关于迭代另一个列表中的列表的问题。

假设我们有两个列表:true_indices_list_1true_indices_list_2

true_indices_list_1包含以下内容。

$`1`
[1] 1, 2, 3, 4

$`2`
[1] 11

$`3`
[1] 33,34

$`4`
[1] 22

$`5`
[1] 11

$`6`
[1] 100

true_indices_list_2 包含以下内容。

$`1`
[1] 5, 6, 7, 8

$`2`
[1] 9

$`3`
[1] 10,11

$`4`
[1] 12

这两个列表都在另一个名为“true_indices_list”的列表中。

现在,这段代码的目的是将相邻的整数添加到列表的每个元素中。例如:

true_indices_list_1应该如下:

$`1`
[1] 1, 2, 3, 4, 5

$`2`
[1] 11, 12

$`3`
[1] 33, 34, 35

$`4`
[1] 22, 23

$`5`
[1] 11, 12

$`6`
[1] 100, 101

AND true_indices_list_2应如下所示:

$`1`
[1] 5, 6, 7, 8, 9

$`2`
[1] 9, 10

$`3`
[1] 10,11, 12

$`4`
[1] 12, 13

为此,我编写了以下代码。

for (i in true_indices_list) {
  
  for (j in seq(1,length(i),1)){
  

i$`j`[length(i$`j`)+1] <-  i$`j`[length(i$`j`)] + 1

  }
  
}

这不起作用..所以我也尝试了这个:

for (i in true_indices_list) {
  
  for (j in seq(1,length(i),1)){
  

i[[j]][length([[j]])+1] <-  [[j]][length([[j]])] + 1

  }
  
}

不幸的是,出了点问题,它不起作用。

如果有人可以帮助我使用此代码,我将不胜感激..

谢谢...

标签: r

解决方案


我认为最好完全没有循环。相反,您可以使用嵌套的lapply. 假设您的数据如下所示:

true_indices_list <- list(
  true_indices_list_1 = list("1" = 1:3,
                             "2" = 5:10,
                             "3" = 34:40),
  true_indices_list_2 = list("1" = 23:27,
                             "2" = 2:8)
  )

true_indices_list$true_indices_list_1
#> $`1`
#> [1] 1 2 3
#> 
#> $`2`
#> [1]  5  6  7  8  9 10
#> 
#> $`3`
#> [1] 34 35 36 37 38 39 40

true_indices_list$true_indices_list_2
#> $`1`
#> [1] 23 24 25 26 27
#> 
#> $`2`
#> [1] 2 3 4 5 6 7 8

然后你可以这样做:

true_indices_list <- lapply(true_indices_list, lapply, function(x) append(x, max(x) + 1))

现在你有

true_indices_list$true_indices_list_1
#> $`1`
#> [1] 1 2 3 4
#> 
#> $`2`
#> [1]  5  6  7  8  9 10 11
#> 
#> $`3`
#> [1] 34 35 36 37 38 39 40 41

true_indices_list$true_indices_list_2
#> $`1`
#> [1] 23 24 25 26 27 28
#> 
#> $`2`
#> [1] 2 3 4 5 6 7 8 9

reprex 包(v0.3.0)于 2020 年 7 月 24 日创建


推荐阅读