user-defined function repeated across multiple columns

Hello,

I am trying to do something simple. But I can't quite figure out how to do it. I have a user defined function called table1

table1 <- dat %>%
group_by(a,b) %>%
summarise(Count = n()) %>%
mutate(Total = sum(Count),  Proportion = Count/Total) %>%
ungroup() %>%
arrange(a, b)

Now, I would like to use lapply to iterate over the function, replacing variable b with a list of column names from my dataframe dat . I have tried the following:

#creating vector
var_names <- list("c", "d", "e", "f")
tables <- lapply(var_names,  function(x) {
table1 <- dat %>%
group_by(a, {{x}}) %>%
summarise(Count = n()) %>%
mutate(Total = sum(Count),  Proportion = Count/Total) %>%
ungroup() %>%
arrange(a, {{x}})
print(table1)
}
)

But I can't get it to work. Any suggestions? Because I am working on a virtual envirnoment, I have only access to base R and dplyr.

replace this with

group_by(a, across(all_of(x)))

This topic was automatically closed 7 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.