r - 在R中的另一个列表中迭代一个列表
问题描述
我有一个关于迭代另一个列表中的列表的问题。
假设我们有两个列表:true_indices_list_1
和true_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
}
}
不幸的是,出了点问题,它不起作用。
如果有人可以帮助我使用此代码,我将不胜感激..
谢谢...
解决方案
我认为最好完全没有循环。相反,您可以使用嵌套的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 日创建
推荐阅读
- azure - 为什么我在为 Runbook 创建 Webhook 时遇到授权失败异常?
- apache - Imgur、Google、Facebook 等网站如何管理这么多独立的网络服务器?
- javascript - 使用javascript(或jquery)在json文件中查找当前成员总数
- javascript - Node.js:在 while-true 循环中承诺
- azure-active-directory - Msal.js getUser() 返回 null
- theorem-proving - 初学者,无法导入精益
- servlets - 如何在没有 web.xml 的情况下使用 JEE7 返回 index.html 页面
- python - tensorflow - object-detection.pbtxt; 没有这样的文件或目录
- reactjs - React.js onClick 事件未触发
- c - C - 这个函数指针声明是什么意思?