making many data frames off simple function

hi I have a function I create below:

output_function <- function(var1, var2) {
data %>%
group_by(!!sym(var1), !!sym(var2)) %>% 
summarize(counts = n()) %>%
ungroup() %>%
mutate(percent = counts / sum(counts))

I want to run this function with several variables as seen below.

cats_color <- output_function("cats_counts", "CATCOLOR")
cats_age <- output_function("cats_counts", "CATAGE")

dogs_color <- output_function("dogs_counts", "DOGCOLOR")
dogs_age <- output_function("dogs_counts", "DOGAGE")

monkeys_color <- output_function("monkeys_counts", "MONKEYCOLOR")
monkeys_age <- output_function("monkeys_counts", "MONKEYAGE")
and so on and so forth

is there a shorter way to do this maybe with a loop? I do want to make a separate dataset for each one. thank you.

you can adapt this pattern:


output_function <- function(var1,var2){
  iris |> filter(Species == !!(var1)) |>
    mutate(v2=!!sym(var2) * 2 )


# a data.frame of what to do ...
(to_do_tbl <- tibble(filt=c("setosa","virginica"),
           mult=c("Petal.Length","Petal.Width")) |> mutate(label=paste0(filt,"_",mult)))

results <- map2(to_do_tbl$filt,
     output_function) |> set_names(to_do_tbl$label)

#its a list of data.frames
str(results,max.level = 1)

#accessing by number or by name ; glimpse to not get flooded by too much info

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.