2014-10-02 79 views
6

替換每個匹配以該對象作爲一個例子:輕鬆找到和在嵌套列表

expr <- substitute(mean(exp(sqrt(.)), .)) 

它是一個嵌套列表。我想找到匹配quote(.)的每個元素。

例如,magrittr的解決方案只是通話的第一級相匹配:

dots <- c(FALSE, vapply(expr[-1], identical, quote(.), 
         FUN.VALUE = logical(1))) 
dots 
[1] FALSE FALSE TRUE 

但我想找到的每一個‘’在任意的嵌套列表中。在這種特殊情況下,這將是這兩個點:

expr[[3]] 
expr[[2]][[2]][[2]] 

,然後將這些點應該更換:

expr[[3]] <- as.name("replacement") 
expr[[2]][[2]][[2]] <- as.name("replacement") 
expr 
# mean(exp(sqrt(replacement)), replacement) 

你會怎麼做呢?

回答

7

使用遞歸函數:

convert.call <- function(x, replacement) { 
    if (is.call(x)) as.call(lapply(x, convert.call, replacement=replacement)) else 
    if (identical(x, quote(.))) as.name(replacement) else 
     x 
} 

convert.call(expr, "x") 
# mean(exp(sqrt(x)), x) 
+0

+1真好看。 – 2014-10-02 04:28:08