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

Replace all values of a recursive list with values of a vector

说,我有以下递归列表:

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:

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

如果您想对嵌套列表的每个元素进行唯一索引,您可以从 rapply() 函数开始,它是 apply() 系列的递归形式。这里我使用了一个特殊的函数,它可以在任何结构的列表中进行唯一索引

rapply(rec_list, 
local({i<-0; function(x) {i<<-i+length(x); i+seq_along(x)-length(x)}}),     
how="replace")

其他函数更简单,例如,如果您只想 seq_along 每个子向量

rapply(rec_list, seq_along, how="replace")