【问题标题】:Easily finding and replacing every match in a nested list轻松查找和替换嵌套列表中的每个匹配项
【发布时间】:2014-10-02 03:50:42
【问题描述】:

以这个对象为例:

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)

你会怎么做?

【问题讨论】:

    标签: r function magrittr


    【解决方案1】:

    使用递归函数:

    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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-01-18
      • 2013-07-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-24
      相关资源
      最近更新 更多