typestar

tidy_pipeline.R en R

Un pipeline tidyverse completo: preparar, resumir y graficar.

#!/usr/bin/env Rscript
# Un pipeline tidyverse completo: transforma, resume y grafica mtcars.

suppressPackageStartupMessages({
  library(dplyr)
  library(tidyr)
  library(ggplot2)
})

cars <- mtcars %>%
  as_tibble(rownames = "model") %>%
  mutate(
    cylinders = factor(cyl),
    transmission = if_else(am == 1, "manual", "automatic"),
    efficiency = case_when(
      mpg < 15 ~ "thirsty",
      mpg < 25 ~ "average",
      TRUE ~ "efficient"
    )
  )

summary_table <- cars %>%
  group_by(cylinders, transmission) %>%
  summarise(n = n(), avg_mpg = round(mean(mpg), 1), .groups = "drop") %>%
  pivot_wider(names_from = transmission, values_from = c(n, avg_mpg))

print(summary_table)

plot <- ggplot(cars, aes(x = wt, y = mpg, colour = cylinders)) +
  geom_point(size = 3) +
  geom_smooth(method = "lm", se = FALSE, linewidth = 0.6) +
  labs(title = "Efficiency by weight", x = "Weight", y = "MPG") +
  theme_minimal()

ggsave("efficiency.png", plot, width = 7, height = 5, dpi = 150)
cat("wrote efficiency.png\n")

Cómo funciona

  1. mutate con case_when deriva columnas etiquetadas.
  2. group_by/summarize y luego pivot_wider arman una tabla.
  3. ggplot la grafica y ggsave escribe la figura.

El intento, en números

Líneas
36
Caracteres a escribir
961
Tokens
225
Ritmo de tres estrellas
110 tpm

Al ritmo de tres estrellas de 110 tokens por minuto, este intento toma unos 123 segundos.

Escribe este fragmento

Paso 1 de 1 en Bis; paso 27 de 27 en dplyr.

← Anterior