Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
836 views
in Technique[技术] by (71.8m points)

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

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

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))

But this doesn't work.

How can I achieve the replacement while keeping the original structure of the list?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can use 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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...