29.10 Build a Linear Model

diamonds2 <- diamonds %>% 
  filter(carat <= 2.5) %>% 
  mutate(log_price = log2(price), log_carat = log2(carat))

mod_diamond <- lm(log_price ~ log_carat, data = diamonds2)

grid <- diamonds2 %>% 
  data_grid(carat = seq_range(carat, 20)) %>% 
  mutate(log_carat = log2(carat)) %>% 
  add_predictions(mod_diamond, "log_price") %>% 
  mutate(price = 2 ^ log_price)

ggplot(diamonds2) +
  aes(carat, price) +
  geom_hex(bins = 50) +
  geom_line(data = grid, color = "red", linewidth = 1)