这里有一个数据的小例子.想象一下我有比这更多的协变量.

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)

I want to create a data.frame that interacts with the group (groupa, groupb, groupc,groupd) and all variables (age, gender weight).
groupa * age
groupa * gender
groupa * weight
Same for the groupb, groupc, and groupd.

I've seen many questions about all possible interaction generators.
But I haven't seen any that show interaction with one column and the rest.
Hope this question was clear enough.

谢谢.

推荐答案

我相信有一个更好的解决方案,但您可以try 编写自己的函数来进行交互,然后使用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

R相关问答推荐

提取具有连续零值的行,如果它们前面有R中的有效值

我正在努力用R计算数据集中的中值逐步距离

如何通过ggplot2添加短轴和删除长轴?

根据现有列的名称和字符串的存在进行变异以创建多个新列

使用rvest从多个页面抓取时避免404错误

基于R中的间隔扩展数据集行

将多个变量组合成宽格式

在gggraph中显示来自不同数据帧的单个值

R中时间间隔的大向量与参考时间间隔的相交

如何在使用因子时获得Sankey图的Scale_Fill_Viridis的全范围

如何构建一个for循环来循环处理动物ID?

如何调整一个facet_work()面板内的框图和移动标签之间的水平宽度?

按组使用dummy r获取高于标准的行的平均值

R将函数参数传递给ggploy

我应该如何解决Raster程序包中未对齐的色条记号?

计算R中各列之间的差异

在一列中创建 colored颜色 标签,在另一列中创建值,图例将两者结合在一起

将来自具有特定条件的两个不同数据帧的列相乘

基于观察次数的滚动总和以及R中每个滚动的开始和结束日期

打印时关闭SF点位置