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