2013-02-01 73 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