making code more generalizable/cleaner

hi everyone! hope ur Wednesday going good. my goal really is to make the two data frames in one clean line of code, and any other cleaning tip would be great. any helps appreciated thank u so much

x <- function(.data, time_group) {
.data %>%
group_by(!!sym(time_group)) %>%
summarize(cat = n()) %>%
ungroup()
}

x_year <- full_data %>% x("year")
x_year_month <- full_data %>% x("year_month")

Questions with a full reprex. See the FAQ are more likely to attract answers than those without.

There are many ways this might be answered; here is one:

library(dplyr)
full_data <- data.frame(x=1:5,
           year=c(rep(2022,4),2023),
           year_month=c(2022*100+1:4,202301))


x <- function(.data, time_group) {
  .data |>
    group_by(!!sym(time_group)) |>
    summarize(cat = n()) |>
    ungroup()
}

xv <- Vectorize(x,
                "time_group",
                SIMPLIFY = FALSE)

full_data |> xv(time_group = c("year",
                               "year_month"))

This topic was automatically closed 42 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.