gpt4 book ai didi

将递归列表的所有值替换为向量的值

转载 作者:行者123 更新时间:2023-12-01 18:12:48 25 4
gpt4 key购买 nike

假设我有以下递归列表:

rec_list <- list(list(rep(1,5), 10), list(rep(100, 4), 20:25))
rec_list
[[1]]
[[1]][[1]]
[1] 1 1 1 1 1

[[1]][[2]]
[1] 10


[[2]]
[[2]][[1]]
[1] 100 100 100 100

[[2]][[2]]
[1] 20 21 22 23 24 25

现在,我想用向量 seq_along(unlist(rec_list)) 替换列表中的所有值,并保留列表的结构。我尝试使用空索引子集,例如

rec_list[] <- seq_along(unlist(rec_list))

但这行不通。

如何在保持列表原有结构的情况下实现替换?

最佳答案

您可以使用重新列出:

relist(seq_along(unlist(rec_list)), skeleton = rec_list)
# [[1]]
# [[1]][[1]]
# [1] 1 2 3 4 5
#
# [[1]][[2]]
# [1] 6
#
#
# [[2]]
# [[2]][[1]]
# [1] 7 8 9 10
#
# [[2]][[2]]
# [1] 11 12 13 14 15 16

关于将递归列表的所有值替换为向量的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30180352/

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