轻松查找并替换嵌套列表中的每个匹配项 [英] Easily finding and replacing every match in a nested list
本文介绍了轻松查找并替换嵌套列表中的每个匹配项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
pre code expr< - substitute(mean(exp(sqrt(。)), 。))
它是一个嵌套列表。我想查找匹配 quote(。)
的所有元素。 例如, magrittr
的解决方案仅匹配调用的第一个级别:
dots < - c( FALSE,vapply(expr [-1],identical,quote(。),
FUN.VALUE = logical(1)))
dots
[1] FALSE FALSE TRUE
但我想找到每个。。在任意的嵌套列表中。在这种情况下,这将是这两个点:$ b
$ b
expr [[3]]
expr [[2] ] [[2]] [[2]]
然后这些点应该被替换: p>
expr [[3]] < - as.name(replacement)
expr [[2]] [ (替换)
表达式
#表示(exp(sqrt(替换)),替换)
你会怎么做? p>使用递归函数:
convert.call< - function(x,replacement){
if( (x,quote(。)))as.name(替换)else
x
convert.call(expr,x)
#mean(exp(sqrt(x)),x)
Take this object as an example:
expr <- substitute(mean(exp(sqrt(.)), .))
It is a nested list. I want to find every element that matches quote(.)
.
For example, magrittr
's solution matches only the first level of the call:
dots <- c(FALSE, vapply(expr[-1], identical, quote(.),
FUN.VALUE = logical(1)))
dots
[1] FALSE FALSE TRUE
But I wanted to find every "." in an arbitrary nested list. In this particular case this would be these two dots:
expr[[3]]
expr[[2]][[2]][[2]]
And then these dots should be replaced:
expr[[3]] <- as.name("replacement")
expr[[2]][[2]][[2]] <- as.name("replacement")
expr
# mean(exp(sqrt(replacement)), replacement)
How would you do this?
解决方案
Using a recursive function:
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)
这篇关于轻松查找并替换嵌套列表中的每个匹配项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文