I am trying to automate a line of code that calls variables. It is in my "summarise" line of code below
library(tidyverse)
# I have three data frames that I want to use later
mro <- c('19100', '19740')
aff <- c('50','80')
yrs <- c(21,22)
# create example data for this post below
yr_pma <- rep(seq(from=2019, to=2021), 5)
set.seed(123)
p50_y22_19100 <- sample(0:12, 15, replace=TRUE)
p80_y22_19100 <- sample(0:12, 15, replace=TRUE)
p50_y21_19100 <- sample(0:12, 15, replace=TRUE)
p80_y21_19100 <- sample(0:12, 15, replace=TRUE)
p50_y21_19740 <- sample(0:12, 15, replace=TRUE)
p80_y21_19740 <- sample(0:12, 15, replace=TRUE)
p50_y22_19740 <- sample(0:12, 15, replace=TRUE)
p80_y22_19740 <- sample(0:12, 15, replace=TRUE)
comb_met <- data.frame(yr_pma, p50_y21_19100, p80_y21_19100, p50_y21_19740, p80_y21_19740,
p50_y22_19100, p80_y22_19100, p50_y22_19740, p80_y22_19740)
comb_met
# create example data for this post above
# This statement is what I want, but I manually type all of the variable names
aff_result <- comb_met %>%
group_by(yr_pma) %>%
summarise(across(c(p50_y21_19100, p80_y21_19100, p50_y21_19740, p80_y21_19740,
p50_y22_19100, p80_y22_19100, p50_y22_19740, p80_y22_19740), sum, na.rm=TRUE))
aff_result
# ?? How can I create the "summarise()" line of code in an automated way from "mro", "aff", and "yrs" so I
# don't have to manually type them
> aff_result
# A tibble: 3 × 9
yr_pma p50_y21_19100 p80_y21_19100 p50_y21_19740
<int> <int> <int> <int>
1 2019 33 29 35
2 2020 40 36 25
3 2021 41 37 19
# ℹ 5 more variables: p80_y21_19740 <int>,
# p50_y22_19100 <int>, p80_y22_19100 <int>,
# p50_y22_19740 <int>, p80_y22_19740 <int>
>