问题
I'm interested in finding out which combination of variables (binge followup sreport age) in my model below produce smallest I2 statistic in rank order (smallest to largest). The I2 from each model is obtained like so:
I2 <- function(x)as.double(x$mod_info$I.2).
Is there a way to automate this in R by looping over formulas?
Ex: First fitting effectsize ~ binge, then effectsize ~ binge + followup then ...
Note: suppose I have the names of all variables stored like so: var.names = c("binge", "followup", "sreport", "age").
library(robumeta)
fit <- robu(effectsize ~ binge + followup + sreport + age, data = get(data(hierdat)),
study = studyid, var = var)
# Get the `I2` for the above model:
I2(fit) # gives 63.993
# Note: I think `lapply(seq_along(var.names), function(i)combn(var.names, i))` can
# give us each combination that should be used in the formula.
回答1:
You can create all combinations of your explanatory variables as you suggest, with a small change (to unlist non-recursively), then convert to formulas:
combos <- unlist(lapply(seq_along(var.names),
function(i) combn(var.names, i, simplify = FALSE)),
recursive = FALSE)
formulae <- lapply(combos,
function(x) paste('effectsize ~', paste(x, collapse = '+')))
Then apply each formula to your data:
fit <- lapply(formulae, function(f)
robu(as.formula(f), data = get(data(hierdat))))
You can then obtain your I2 on each member of the fit, and then a which.min() will give you the one with the smallest I2.
来源:https://stackoverflow.com/questions/58756403/combinations-of-variables-that-produce-the-smallest-quantities-in-an-r-function