引用条款列表中的公式

时间:2015-05-20 07:59:45

标签: r formula

说我有一个引用条款列表:

l <- list(quote(x), quote(y), quote(I(z + 10)))

我希望将其变成(单面)公式:

~ x + y + I(z + 10)

最简单的方法是将所有内容转换为文本并从头开始构建公式,即deparse / reparse:

formula(paste("~", paste(l, collapse="+")))

,在幕后,相当于

formula(paste("~", paste(sapply(l, deparse), collapse="+")))

但这似乎有点不优雅,并且可能倾向于解析螺旋上升。有没有办法用纯语言操作来获得公式?

1 个答案:

答案 0 :(得分:0)

通过按术语建立公式RHS术语,可以以纯粹的象征性方式做到这一点。

l <- list(quote(x), quote(y), quote(I(z + 10)))
out <- l[[1]]
for(i in seq_along(l)[-1])
{
    out <- substitute(a + b, list(a=out, b=l[[i]]))
}
out <- call("~", out)
out
# ~x + y + I(z + 10)

请注意,out 看起来像一样,但实际上是类(和模式)call。要将其转换为实际公式,请使用as.formula

f <- as.formula(out)

但是,将输出保留为调用对象有时会有利。特别是,如果术语数量非常大,则创建公式会导致堆栈溢出:

X <- paste0("x", 1:1e5)
X <- lapply(X, as.name)

out <- X[[1]]
for(i in seq_along(X)[-1])
{
    out <- substitute(a + b, list(a=out, b=X[[i]]))
}

# this still works
out <- call("~", out)

f <- as.formula(out)
# Error: protect(): protection stack overflow