phargart
phargart

Reputation: 729

Separating categorical variables in a linear regression

I fit a linear model using two categorical variables and one numerical variable as follows:

data(iris)

iris2 <- iris %>%
  mutate(petal_type= if_else(Petal.Length > 4, "petal_long", "petal_short"),
         sepal_type = if_else(Sepal.Length > 6, "flower_long", "flower_short")
         )

lm(Sepal.Width ~ sepal_type*petal_type + petal_type*Petal.Width, data = iris2)

# Coefficients:
#                         (Intercept)                        sepal_typeflower_short                          petal_typepetal_short  
#                                    2.48793                                      -0.08721                                       1.51070  
#                                 Petal.Width  sepal_typeflower_short:petal_typepetal_short             petal_typepetal_short:Petal.Width  
#                                     0.27131                                      -0.28965                                      -1.19334  

I want to separate out the two categorical variables to get an estimate of the intercept and slope for each dummy variable. I would like to create a table like this that would describe the relationship between sepal.width and petal.width:

sepal_type     petal_type        Intercept_estimate          Slope_estimate 
flower_short   petal_short
flower_short   petal_long
flower_long    petal_short
flower_long    petal_long

I can do this by hand using different contrasts, but is there an easy way? Thanks!

Upvotes: 0

Views: 70

Answers (1)

Onyambu
Onyambu

Reputation: 79338

iris2 %>%
  group_by(petal_type, sepal_type) %>%
  summarise(model = list(coef(lm(Sepal.Width~Petal.Width))),
            .groups = 'drop')%>%
  unnest_wider(model)

 petal_type  sepal_type   `(Intercept)` Petal.Width
  <chr>       <chr>                <dbl>       <dbl>
1 petal_long  flower_long           2.33      0.355 
2 petal_long  flower_short          2.86     -0.0186
3 petal_short flower_long           2.8      NA     
4 petal_short flower_short          3.62     -0.922 

Upvotes: 1

Related Questions