2013-02-01 74 views
7

我有这样的列表:查找嵌套列表中元素的索引?

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

是否有(无环的)的方式来识别元件,例如的位置如果我想用5来代替“C”的值,它哪里并不重要元素“C”被发现,我可以这样做:

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

我已经试过grepl,并在当前例如,下面的工作:

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

但这需要一个嵌套级别的假设。

,我想问的是,我有参数值的深列表,以及替换值的命名载体,我想这样做

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

这是一个适应我刚才的问题的原因,update a node (of unknown depth) using xpath in R?,使用R列表代替XML

回答

7

一种方法是使用unlistrelist

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) 

因为从不公开列表名称与.连接在一起,你需要小心grep和您的参数是如何命名的。如果您的任何列表名称中没有.,则应该没问题。否则,像list(.C = 1)这样的名字将落入该模式并被替换。

1

基于this question,你可以尝试递归像这样:

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

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