Find item indices in a nested list?

I have a list like:

mylist <- list(a = 1, b = list(A = 1, B = 2), c = list(C = 1, D = 3)) 

there is (without a loop) a way to identify the positions of elements, for example. if I want to replace the values ​​of "C" with 5, and it does not matter where the element "C" is, can I do something like:

 Aindex <- find_index("A", mylist) mylist[Aindex] <- 5 

I tried grepl and the following will work in the current example:

 mylist[grepl("C", mylist)][[1]][["C"]] 

but this requires an assumption about the level of nesting.

The reason I ask is because I have a deep list of parameter values ​​and a named vector of replacement values, and I want to do something like

  replacements <- c(a = 1, C = 5) for(i in names(replacements)){ indx <- find_index(i, mylist) mylist[indx] <- replacements[i] } 

Is this an adaptation to my previous question, update node (of unknown depth) using xpath in R? using R lists instead of XML

+7
list r recursion nested
source share
2 answers

One method is to use unlist and relist .

 mylist <- list(a = 1, b = list(A = 1, B = 2), c = list(C = 1, D = 3)) tmp <- as.relistable(mylist) tmp <- unlist(tmp) tmp[grep("(^|.)C$",names(tmp))] <- 5 tmp <- relist(tmp) 

Because the names of the lists from the list are combined with . , you need to be careful with grep and how your parameters will be named. If there are no lists in any of your names . That should be good. Otherwise, names such as list(.C = 1) will fall into the template and be replaced.

+7
source share

Based on this question , you can try this recursively:

 find_and_replace <- function(x, find, replace){ if(is.list(x)){ n <- names(x) == find x[n] <- replace lapply(x, find_and_replace, find=find, replace=replace) }else{ x } } 

Testing in the deeper mylist :

 mylist <- list(a = 1, b = list(A = 1, B = 2), c = list(C = 1, D = 3, d = list(C=10, D=55))) find_and_replace(mylist, "C", 5) $a [1] 1 $b $b$A [1] 1 $b$B [1] 2 $c $c$C ### it worked [1] 5 $c$D [1] 3 $c$d $c$d$C ### it worked [1] 5 $c$d$D [1] 55 
+1
source share

All Articles