Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 503
DatamineR Avatar asked May 12 '15 01:05

DatamineR


2 Answers

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
like image 97
A5C1D2H2I1M1N2O1R2T1 Avatar answered Nov 01 '22 11:11

A5C1D2H2I1M1N2O1R2T1


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")
like image 29
MrFlick Avatar answered Nov 01 '22 10:11

MrFlick