# This script follows loosely  the beginning of chapter 26 of the book "R for Data Science" (2nd edition)
# ITERATION

library(tidyverse)

df <- tibble(
  a = rnorm(10),
  b = rnorm(10),
  c = rnorm(10),
  d = rnorm(10)
)

# Let's compute the number of observations and the median of each column. We could
# just copy-and-paste.

df %>%
  summarize(
    n = n(),
    a = median(a),
    b = median(b),
    c = median(c),
    d = median(c)
  )

# However, function across() is less tedious.
df %>% 
  summarize(
    n = n(),
    across(a:d, median)
  )

# everything() selects every (non-grouping) column.
df <- tibble(
  grp = sample(2, 10, replace = TRUE),
  a = rnorm(10),
  b = rnorm(10),
  c = rnorm(10),
  d = rnorm(10)
)
df

df %>% group_by(grp) %>% summarise(across(everything(), median))

# where() allows columns selection based on their type.

letters # `letters` is just a vector containing the Latin alphabet
df2 <- df %>% mutate(txt = letters[1:10])
df2

df2 %>% group_by(grp) %>% summarize(across(where(is.numeric), median))

# Error - we pass the median function for across() to call - median. We are not
# calling the median function ourselves - median().
df %>% group_by(grp) %>% summarise(across(everything(), median()))
