r 运行 对数据子集的硬编码回归

r run hardcoded regression on subset of data

如果这是我的数据集:

dataset <- data.frame(
           ID = 1:6,
           Group = c("Red", "Red", "Blue", "Red", "Blue", "Blue"),
           X = c(10, 11, 11, 12, 9, 13))
ID Group X
1 Red 10
2 Red 11
3 Blue 11
4 Red 12
5 Blue 9
6 Blue 13

我有两个线性回归方程:

 (Eq. 1) Y ~ 34    + 0.35 * X [ where Group == "Red" ]
 (Eq. 2) Y ~ 33.67 + 0.37 * X [ where Group == "Blue"]

如何使用我的数据集从这个回归问题中预测 Y?

Tidyverse 解决方案是

library(tidyverse)
dataset %>% mutate(Y = ifelse(Group == "Red", 34    + 0.35 * X, 33.67 + 0.37 * X ))

这假设您只有红色和蓝色的组名称。