Combinations of variables that produce the smallest quantities in an R function

一曲冷凌霜 提交于 2019-11-27 06:31:11

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!