R中的交互项循环

c3frrgcw  于 2022-12-06  发布在  其他
关注(0)|答案(1)|浏览(133)

这里有一个小的数据例子,假设我有比这个更多的协变量。

install.packages("mltools")
library(mltools)
library(dplyr)
set.seed(1234)

data <- tibble::data_frame(
  age = round(runif(60, min = 48, max = 90)),
  gender = sample(c(0,1), replace=TRUE, size=60),
  weight = round(runif(60, min = 100, max = 300)),
  group = sample(letters[1:4], size = 60, replace = TRUE))

one_hot <- data[,c("group")] %>% 
  glmnet::makeX() %>%
  data.frame()
data$group <- NULL
data <- cbind(data, one_hot)

我想创建一个与组(groupa,groupb,groupc,groupd)和所有变量(年龄,性别,体重)交互的数据框架。
群a * 年龄
性别
组a * 重量
组b、组pc和组pd也是如此。
我看到了很多关于所有可能的交互发生器的问题。
但我还没有看到任何显示与一列和其余的互动。
希望这个问题问得够清楚。

  • 谢谢-谢谢
cngwdvgl

cngwdvgl1#

我相信有一个更好的解决方案,但是您可以尝试编写自己的函数来进行交互,然后使用apply遍历列,使用do.call合并所有内容:

intfun <- function(var){
  data %>% 
    mutate(across(starts_with("group"),~.*{{var}})) %>%
    select(starts_with("group"))
}

int_terms <- cbind(data, 
                   do.call(cbind, apply(data[,1:3], 2, function(x) intfun(x))))

输出(请注意,此处并未显示所有列):

# > head(int_terms)
# age gender weight groupa groupb groupc groupd age.groupa age.groupb age.groupc age.groupd gender.groupa gender.groupb gender.groupc gender.groupd weight.groupa
# 1  88     33    113      0      1      0      0          0         88          0          0             0            33             0             0             0
# 2  49     33    213      1      0      0      0         49          0          0          0            33             0             0             0           213
# 3  83     33    152      1      0      0      0         83          0          0          0            33             0             0             0           152
# 4  75     33    101      0      1      0      0          0         75          0          0             0            33             0             0             0
# 5  61     33    218      0      1      0      0          0         61          0          0             0            33             0             0             0
# 6  79     33    204      1      0      0      0         79          0          0          0            33             0             0             0           204

相关问题