library(tidyverse)
library(glue)
library(gt)
# reshape anscombe data in tidy format
ans <-
anscombe |>
as_tibble() |>
pivot_longer(x1:y4) |>
mutate(dataset = case_when(str_detect(name, "1") ~ "dataset1",
str_detect(name, "2") ~ "dataset2",
str_detect(name, "3") ~ "dataset3",
str_detect(name, "4") ~ "dataset4")) |>
mutate(xory = ifelse(str_detect(name, "x"), "x", "y")) |>
select(-name) |>
pivot_wider(names_from = xory, values_from = value, values_fn = list) |>
unnest(cols = c("x","y"))
# Define a function to make labels for plots
labler <- function(rsq,pval) glue("R = {rsq}, p = {pval}")
# generate linear models, extract p-vals and rsq; generate labels
ans_sum <-
ans |>
group_by(dataset) |>
nest() |>
mutate(linmod = map(data, \(data)
lm(y~x, data = data)),
linmod_s = map(linmod, summary),
rsq = map_dbl(linmod_s, \(sum) round(sqrt(sum$r.squared),3)),
pval = map_chr(linmod_s, \(sum) scales::pvalue(sum$coefficients[2,4])),
label = map2_chr(rsq, pval, labler))
ans_plot <-
ans |>
ggplot(aes(x = x, y = y)) +
geom_point() +
facet_wrap(.~dataset, nrow = 2) +
theme_bw()
ans_plot