Pass function arguments that are variable names into formulae in R functions? -
i looking simple way pass function arguments variable names formulae in r functions.
test dataset:
set.seed(4892) df.pass <- data.frame("alfa"=sample(1:9, 100, replace=t), "beta"=sample(1:9, 100, replace=t), "theta"=sample(1:9, 100, replace=t), "out"=runif(100, 0, 1))
example analysis (testing if interaction model different) made function:
lrtest(glm(out~alfa*beta, family = binomial("logit"), df.pass), glm(out~alfa + beta, family = binomial("logit"), df.pass))
if goal create generic function invinteract
solves problem above arbitrary variable names , data sets, simplest way pass variable names function()
arguments formulae terms corresponding positions of out
, alfa
, beta
?
inserting raw variable names formulae not work, because r tries evaluate names objects , finds nothing.
inserting string variable names directly formulae not work either.
is necessary reconstruct formulae paste()
, or there more direct way?
glm
accepts character string instead of formula. thus, can this:
mytest <- function(df, y, x1, x2) { lrtest(glm(sprintf("%s ~ %s * %s", y, x1, x2), family = binomial("logit"), df), glm(sprintf("%s ~ %s + %s", y, x1, x2), family = binomial("logit"), df)) } mytest(df.pass, "out", "alfa", "beta")
Comments
Post a Comment