从列生成回归公式

Generate a regression formula from columns

我正在尝试生成一个模型,用于使用负二项式回归自动分析变量及其相互作用。我取得了一些进展(主要感谢 SO :-),现在我想生成回归字符串以传递到 neg bin 模型和 stepaic 函数。

有什么想法吗?

这是我的代码

library(dplyr)
library(purrr)
library(stringr)
df<- nycflights13::weather
interactions <- c("hour","dewp","humid","wind_dir","wind_speed")
target_col<- "temp"
out <- combn(interactions, 2, function(x) df %>%
               dplyr::select(x) %>%
               transmute(!! str_c(x, collapse="_"):= reduce(., `*`)),
             simplify = FALSE) %>% 
  bind_cols %>% 
  bind_cols(df, .)

target_formula<- target_col ~ interactions + combinations
model <- glm.nb(target_formula, data=df)
model<- stepaic(model)

我看到您有 5 个要在公式中使用的变量。而且您还想包括交互。

那你为什么不试试这个方法:

df <- nycflights13::weather
interactions <- c("hour","dewp","humid","wind_dir","wind_speed")
target_col <- "temp"
target_formula <- as.formula(sprintf("%s ~ (%s)^2", 
                             target_col, 
                             paste(interactions, collapse = " + ")))
model <- MASS::glm.nb(target_formula, data = df)
model <- MASS::stepAIC(model)

编辑

如果你只想计算一些变量的交互作用,你可以这样做:

df<- nycflights13::weather
vars <- c("hour","dewp","humid","wind_dir","wind_speed", 
          "wind_dir:wind_speed", "dewp:humid")
target_col <- "temp"
target_formula <- as.formula(sprintf("%s ~ %s", 
                                     target_col, 
                                     paste(vars, collapse = " + ")))
model <- MASS::glm.nb(target_formula, data = df)
model <- MASS::stepAIC(model)

只需按照 var1:var2.

这样的格式将它们添加到 vars

编辑 2

如果只需要所有部分变量之间的交互作用,可以按如下方式进行:

df<- nycflights13::weather
singles <- c("hour","dewp")
interactions <- c("humid","wind_dir","wind_speed")
target_col <- "temp"

target_formula <- as.formula(sprintf("%s ~  %s + (%s)^2", 
                                     target_col, 
                                     paste(singles, collapse = " + "),
                                     paste(interactions, collapse = " + ")))
model <- MASS::glm.nb(target_formula, data = df)
model <- MASS::stepAIC(model)

问题是您将获得所有交互:例如,如果您不想要 humid:wind_dir,则此解决方案不是您要找的。

如果您只需要特定的交互,则需要使用之前的编辑。

如果你想使用除部分交互之外的大部分交互,还有其他方法,但如果你有特定的规则,我们可以想出一些高效的方法。

例如,像这样:

setdiff(combn(c("humid","wind_dir","wind_speed"), 2, paste, collapse = ":"), "humid:wind_dir")
#> [1] "humid:wind_speed"    "wind_dir:wind_speed"

使用 reformulate 创建没有交互作用的公式,然后 update 它包含交互作用:

rhs_vars <- c("hour","dewp","humid","wind_dir","wind_speed")
target <- "temp"

update(reformulate(rhs_vars, target), . ~ (.)^2)

给这个公式对象:

temp ~ hour + dewp + humid + wind_dir + wind_speed + hour:dewp + 
    hour:humid + hour:wind_dir + hour:wind_speed + dewp:humid + 
    dewp:wind_dir + dewp:wind_speed + humid:wind_dir + humid:wind_speed + 
    wind_dir:wind_speed