I learned in this question's comment by @amoeba that
Also, the difference between "building separate models" and "using categorical variable" is not clear to me.
activity ~ condition + species + condition*species
- this usesspecies
as categorical variable, but this is fully equivalent to a separate regressionactivity ~ condition
for each species separately.
I did a numerical example and observed they are the same (by checking the difference between two vectors). But how to mathematically proof this? I think it is related to design matrix with categorical variable dummy coding?
PS: here is my my numerical experiment
# code to show build model for each cut group is equal to using the formula
# price ~ carat + cut + carat * cut
# -------------------------------------------------------------------------
# make data, 3 classes, only 1 feature
# -------------------------------------------------------------------------
library(dplyr)
d=ggplot2::diamonds
d=d[,c("cut","carat","price")]
d=subset(d,cut %in% c("Very Good","Premium","Ideal"))
d$cut=factor(d$cut, ordered=F)
d
# -------------------------------------------------------------------------
# method 1, build 3 models for each class by using subsets
# -------------------------------------------------------------------------
s1=subset(d,cut=="Very Good")
fit1=lm(price ~ carat,s1)
p_s1=predict(fit1,s1)
s2=subset(d,cut=="Premium")
fit2=lm(price ~ carat,s2)
p_s2=predict(fit2,s2)
s3=subset(d,cut=="Ideal")
fit3=lm(price ~ carat,s3)
p_s3=predict(fit3,s3)
# -------------------------------------------------------------------------
# method 2, build 3 models by using interaction in formula
# -------------------------------------------------------------------------
fit0=lm(price ~ carat + cut + carat * cut,d)
p0=predict(fit0,d)
# -------------------------------------------------------------------------
# show they are the same
# -------------------------------------------------------------------------
# sort and show they are the same
d_ext=cbind(d,p=p0)
d2_ext=rbind(cbind(s1,p=p_s1),cbind(s2,p=p_s2),cbind(s3,p=p_s3))
d_ext=arrange(d_ext,cut,carat,price)
d2_ext=arrange(d2_ext,cut,carat,price)
norm(as.matrix((d_ext$p-d2_ext$p)))