R 在嵌套列表中查找元素的索引?

R 在嵌套列表中查找元素的索引?,r,list,recursion,nested,R,List,Recursion,Nested,我有这样一个清单: mylist <- list(a = 1, b = list(A = 1, B = 2), c = list(C = 1, D = 3)) 但这需要对嵌套级别进行假设 我问这个问题的原因是,我有一个参数值的深度列表,和一个替换值的命名向量,我想做一些类似的事情 replacements <- c(a = 1, C = 5) for(i in names(replacements)){ indx <- find_index(i, mylist)

我有这样一个清单:

mylist <- list(a = 1, b = list(A = 1, B = 2), c = list(C = 1, D = 3))
但这需要对嵌套级别进行假设

我问这个问题的原因是,我有一个参数值的深度列表,和一个替换值的命名向量,我想做一些类似的事情

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

替换一种方法是使用
取消列表
重新列表

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)
mylist基于,您可以像这样递归地尝试它:

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

现在也可以使用
rrapply
-包(base
rapply
的扩展版本)中的
rrapply
完成此操作。要根据元素名称返回元素在嵌套列表中的位置,可以使用特殊参数
.xpos
.xname
。例如,要查找名为“C”的元素的位置,请执行以下操作:

库(rrapply)
mylist 3 1
然后,我们可以使用以下命令更新嵌套列表中的值:

## update value C-node
mylist[[Cindex]] <- 5
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
  }
}
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
## update value C-node
mylist[[Cindex]] <- 5