从R中的函数调用中获取公式的元素

时间:2016-06-16 16:44:11

标签: r

我为包含matrix的类定义了一个方法,如:

setMethod(
    f = "test",
    signature = "MatrixSet",
    definition = function(object, ..., test, nme, subset, verbose = TRUE) {
          dta = object@matrix
          ## some changes in dta
          mod <- glm(..., data = dta)

          ## here I need to take the argument "formula" from "..."
          mod0 <- update(mod, as.formula(paste0(". ~ . - ", all.vars(formula)[1])))
          effect <- c(mod$coef[2], suppressMessages(confint(mod)[2,]))
          p <- anova(mod, mod0, test = test)
          p2 <- p[[nme]][2]

          return(list(effect=effect, p=p2))
    }
)

所以,要从formula获取...参数,我试过了:

arg <- as.lsit(match.call())

arg的内容告诉我:

> arg
[[1]]
.local

$object
object

$formula
..1

$family
..2

$test
[1] "F"

$nme
[1] "Pr(>F)"

那么......我如何从$formula获取arg真实内容?

我调用的函数如下:

test(dtaContained, formula=flu~PFHxS+age+sex, 
    family = gaussian, test = "F", nme = "Pr(>F)")

1 个答案:

答案 0 :(得分:1)

似乎问题与R环境和类环境之间的嵌套环境有关。

可能的解决方案是:

arg <- match.call(test, sys.call(sys.parent()), expand.dots=FALSE)

所以arg的内容是:

> arg
test(object = dtaContained, ... = pairlist(formula = flu ~ PFHxS + age + 
    sex, family = gaussian, test = "F", nme = "Pr(>F)"))

因此我得到了以下公式:

> as.list(arg)$...$formula
flu ~ PFHxS + age + sex

我愿意接受任何可以改进这种方式的答案,或者用更多细节补充它。