gpt4 book ai didi

r - 轻松查找和替换嵌套列表中的每个匹配项

转载 作者:行者123 更新时间:2023-12-04 11:39:17 24 4
gpt4 key购买 nike

以这个对象为例:

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)

你会怎么做?

最佳答案

使用递归函数:

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)

关于r - 轻松查找和替换嵌套列表中的每个匹配项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26154252/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com