Intro Thoughts
Status Quo
library(devtools)
create(".")
knitrExtra:::chunk_to_r("StatLm")
## It seems you are currently knitting a Rmd/Qmd file. The parsing of the file will be done in a new R session.
compute_panel_lm <- function(data, scales, drop_x = FALSE, formula = y ~ . ){
data |>
ggplot2::remove_missing() ->
data
data %>%
select(-PANEL) ->
lmdata
if(drop_x){
lmdata %>%
select(-x) ->
lmdata
}
lm <- lm(data = lmdata, formula = formula)
data$yend = data$y
data$y = lm$fitted.values
data$xend = data$x
data$residuals <- lm$residuals
data
}
StatLm <- ggplot2::ggproto("StatLm",
ggplot2::Stat,
compute_panel = compute_panel_lm)
Experiment
library(tidyverse)
palmerpenguins::penguins %>%
remove_missing() %>%
select(y = flipper_length_mm,
x = bill_depth_mm,
pred1 = sex) %>%
mutate(PANEL = 1) %>%
compute_panel_lm()
## Warning: Removed 11 rows containing missing values or values outside the scale
## range.
## # A tibble: 333 × 7
## y x pred1 PANEL yend xend residuals
## <dbl> <dbl> <fct> <dbl> <int> <dbl> <dbl>
## 1 200. 18.7 male 1 181 18.7 -19.0
## 2 192. 17.4 female 1 186 17.4 -5.94
## 3 189. 18 female 1 195 18 6.39
## 4 181. 19.3 female 1 193 19.3 11.6
## 5 189. 20.6 male 1 190 20.6 0.560
## 6 190. 17.8 female 1 181 17.8 -8.72
## 7 195. 19.6 male 1 195 19.6 -0.00157
## 8 191. 17.6 female 1 182 17.6 -8.83
## 9 186. 21.2 male 1 191 21.2 4.90
## 10 187. 21.1 male 1 198 21.1 11.3
## # ℹ 323 more rows
palmerpenguins::penguins %>%
ggplot() +
aes(y = flipper_length_mm, x = bill_depth_mm) +
geom_point() +
geom_point(stat = StatLm, alpha = .25, formula = y ~ species) +
geom_segment(stat = StatLm, alpha = .25) +
aes(color = species) + aes(species = species) +
aes(shape = sex) +
aes(body_mass_g = body_mass_g) +
aes(bill_length_mm = bill_length_mm) +
aes(island = island) +
aes(year = year)
## Warning: Removed 11 rows containing missing values or values outside the scale range.
## Removed 11 rows containing missing values or values outside the scale range.
## Warning: Removed 11 rows containing missing values or values outside the scale range
## (`geom_point()`).