Easily finding and replacing every match in a nested list

流过昼夜 提交于 2019-12-04 01:24:39

问题


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?


回答1:


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)


来源:https://stackoverflow.com/questions/26154252/easily-finding-and-replacing-every-match-in-a-nested-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!