── Attaching core tidyverse packages ────────────── tidyverse 2.0.0 ──
✔ dplyr 1.1.4 ✔ readr 2.1.5
✔ forcats 1.0.0 ✔ stringr 1.5.1
✔ ggplot2 4.0.0 ✔ tibble 3.3.0.9004
✔ lubridate 1.9.4 ✔ tidyr 1.3.1
✔ purrr 1.1.0
── Conflicts ──────────────────────────────── tidyverse_conflicts() ──
✖ dplyr::filter() masks stats::filter()
✖ dplyr::lag() masks stats::lag()
ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors
# Given data
total_registered <- 771
# Responses by age group
responses <- tribble(
~age_group , ~against , ~legalize , ~not_sure ,
"18-49" , 59 , 292 , 391 - (59 + 292) ,
"50+" , 67 , 245 , (771 - 391) - (67 + 245)
)
# Calculate total per group
responses <- responses %>%
mutate(total = against + legalize + not_sure)
# Then calculate proportions of each age group in the total sample
age_props <- responses %>%
summarise(
total_18_49 = sum(total[age_group == "18-49"]),
total_50_plus = sum(total[age_group == "50+"])
) %>%
pivot_longer(everything(), names_to = "age_group", values_to = "count") %>%
mutate(
age_group = recode(
age_group,
"total_18_49" = "18-49",
"total_50_plus" = "50+"
),
proportion = count / total_registered
)
# Show both tables
list(
responses_by_age = responses,
proportions_by_age = age_props
)$responses_by_age
# A tibble: 2 × 5
age_group against legalize not_sure total
<chr> <dbl> <dbl> <dbl> <dbl>
1 18-49 59 292 40 391
2 50+ 67 245 68 380
$proportions_by_age
# A tibble: 2 × 3
age_group count proportion
<chr> <dbl> <dbl>
1 18-49 391 0.507
2 50+ 380 0.493
