Reputation: 77
I have a data frame PlotData_df
with 3 columns: Velocity
(numeric), Height
(numeric), Gender
(categorical).
Velocity Height Gender
1 4.1 3.0 Male
2 3.1 4.0 Female
3 3.9 2.4 Female
4 4.6 2.8 Male
5 4.1 3.3 Female
6 3.1 3.2 Female
7 3.7 3.0 Male
8 3.6 2.4 Male
9 3.2 2.7 Female
10 4.2 2.5 Male
I used the following to give regression equation for complete data:
c <- lm(Height ~ Velocity, data = PlotData_df)
summary(c)
# Estimate Std. Error t value Pr(>|t|)
# (Intercept) 4.1283 1.0822 3.815 0.00513 **
# Velocity -0.3240 0.2854 -1.135 0.28915
# Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
# Residual standard error: 0.4389 on 8 degrees of freedom
# Multiple R-squared: 0.1387, Adjusted R-squared: 0.03108
# F-statistic: 1.289 on 1 and 8 DF, p-value: 0.2892
a <- signif(coef(c)[1], digits = 2)
b <- signif(coef(c)[2], digits = 2)
Regression <- paste0("Velocity = ",b," * Height + ",a)
print(Regression)
# [1] "Velocity = -0.32 * Height + 4.13"
How can I extend this to display two regression equations (depending on whether Gender is Male or Female)?
Upvotes: 1
Views: 323
Reputation: 73265
How can I extend this to display two regression equations (depending on whether Gender is Male or Female)?
You need a linear model with interaction between Height
and Gender
first. Try:
fit <- lm(formula = Velocity ~ Height * Gender, data = PlotData_df)
Then if you want to display fitted regression function / equation. You should use two equations, one for Male
, one for Female
. There is really no other way, because we decide to plug in coefficients / numbers. The following shows you how to get them.
## formatted coefficients
beta <- signif(fit$coef, digits = 2)
# (Intercept) Height GenderMale Height:GenderMale
# 4.42 -0.30 -1.01 0.54
## equation for Female:
eqn.female <- paste0("Velocity = ", beta[2], " * Height + ", beta[1])
# [1] "Velocity = -0.30 * Height + 4.42"
## equation for Male:
eqn.male <- paste0("Velocity = ", beta[2] + beta[4], " * Height + ", beta[1] + beta[3])
# [1] "Velocity = 0.24 * Height + 3.41"
If you are unclear why
Male
is beta[1] + beta[3]
;Male
is beta[2] + beta[4]
,you need to read around ANOVA and contrast treatment for factor variables. This question on Cross Validated: How to interpret dummy and ratio variable interactions in R has a very similar setting to yours. I made a very brief answer there on the interpretation of coefficients, so maybe you could have a look.
Upvotes: 1