16

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?

0

2 Answers 2

24

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
1
  • 7
    Oh come on, how did you find that function so quickly! :-0 May 12, 2015 at 1:47
5

If you wanted to uniquely index each element of a nested list, you could start with the rapply() function which is the recursive form of the apply() family. Here I use a special function that can uniquely index across a list of any structure

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

other functions are simplier, for example if you just wanted to seq_along each subvector

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.