用向量的值替换递归列表的所有值 [英] Replace all values of a recursive list with values of a vector

查看:58
本文介绍了用向量的值替换递归列表的所有值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说,我有以下递归列表:

Say, I have the following recursive list:

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))替换列表的所有值,并保留列表的结构.我尝试使用空索引子设置,例如

Now, I would like to replace all the values of the list, say, with the vector seq_along(unlist(rec_list)), and keep the structure of the list. I tried using the empty index subsetting like

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

但这是行不通的.

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

How can I achieve the replacement while keeping the original structure of the 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

这篇关于用向量的值替换递归列表的所有值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆