Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Updating a value in a nested list by having the position as an integer vector

Let’s consider I have a nested list

x = list(a1 = list(b1 = list(c1 = 1), b2 = list(d1 = 1, d2 = 2, d3 = 3)))

Further I have an index, giving me the position in the nested list, and a value that I want to update

index = c(1,1,1) # should update c1
value = 100

Manually I can do is as follows

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

x[[1]][[1]][1] = value
x

I also know I can write it as such

index = c(1,2,2) # should update d2
`[[`(`[[`(`[[`(x, 1), 2), 2) = value
x

Question: Is there a programmatic way to set the value at index for the nested list?

To only read the value I could go the following way – but it does not allow me to change it.

ifuns <- lapply(index, function(i) {function(x) `[[`(x, i)})
Funcall <- function(f, ...) f(...)
Reduce(Funcall, rev(ifuns), x, right = TRUE)

This (obviously) fails

Reduce(Funcall, rev(ifuns), x, right = TRUE) <- value
Error in Reduce(Funcall, rev(ifuns), x, right = TRUE) <- value : 
  could not find function "Reduce<-"

>Solution :

Are you looking for this?

x[[index]] <- value

# > x
# $a1
# $a1$b1
# $a1$b1$c1
# [1] 100
# 
# 
# $a1$b2
# $a1$b2$d1
# [1] 1
# 
# $a1$b2$d2
# [1] 2
# 
# $a1$b2$d3
# [1] 3
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading