Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/78.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 用向量值替换递归列表的所有值_R_List_Recursion_Subset - Fatal编程技术网

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

R 用向量值替换递归列表的所有值,r,list,recursion,subset,R,List,Recursion,Subset,比如,我有以下递归列表: 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 但这不起作用 如何在保持列表的原始结构的同时实现替换?您可以使用重新列表:

比如,我有以下递归列表:

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
但这不起作用


如何在保持列表的原始结构的同时实现替换?

您可以使用
重新列表

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

如果要唯一地索引嵌套列表的每个元素,可以从
rappy()
函数开始,该函数是
apply()
族的递归形式。在这里,我使用一个特殊的函数,它可以唯一地索引任何结构的列表

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

哦,得了吧,你怎么这么快就找到那个函数了!:-0漂亮!:-)谢谢
rapply(rec_list, 
local({i<-0; function(x) {i<<-i+length(x); i+seq_along(x)-length(x)}}),     
how="replace")
rapply(rec_list, seq_along, how="replace")