在嵌套列表中找到元素的索引? [英] Find the indices of an element in a nested list?
问题描述
我有一个类似的列表:
mylist <- list(a = 1, b = list(A = 1, B = 2), c = list(C = 1, D = 3))
是否有(无环)标识元素位置的方法,例如如果我想将"C"的值替换为5,并且无论在哪里找到"C"元素,我都可以执行以下操作:
is there an (loop-free) way to identify the positions of the elements, e.g. if I want to replace a values of "C" with 5, and it does not matter where the element "C" is found, can I do something like:
Aindex <- find_index("A", mylist)
mylist[Aindex] <- 5
我已经尝试过grepl
,在当前示例中,以下方法将起作用:
I have tried grepl
, and in the current example, the following will work:
mylist[grepl("C", mylist)][[1]][["C"]]
但这需要假设嵌套级别.
but this requires an assumption of the nesting level.
我问的原因是我有一个很深的参数值列表,以及一个替换值的命名向量,我想做类似的事情
The reason that I ask is that 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]
}
这是我以前的问题的改编,使用R中的xpath更新(未知深度)节点,,使用R列表而不是XML
this is an adaptation to my previous question, update a node (of unknown depth) using xpath in R?, using R lists instead of XML
推荐答案
一种方法是使用unlist
和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)
由于unlist中的列表名称与.
串联在一起,因此在使用grep
以及如何命名参数时要格外小心.如果您的任何列表名称中都没有.
,应该没问题.否则,list(.C = 1)
之类的名称将落入该模式并被替换.
Because list names from unlist are concatenated with a .
, you'll need to be careful with grep
and how your parameters are named. If there is not a .
in any of your list names, this should be fine. Otherwise, names like list(.C = 1)
will fall into the pattern and be replaced.
这篇关于在嵌套列表中找到元素的索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!