use Dinamically generated column names in dplyr

I have a data frame with multiple columns, the user provides a vector with the column names, and i want to count maximum amount of times an element appears

df <- tibble(
  var1 = sample(c(1:3),10,replace=T),
  var2 = sample(c(1:3),10,replace=T),
  var3 = sample(c(1:3),10,replace=T)
)
select_vars <- c("var2", "var3")

df %>% 
    rowwise() %>% 
    mutate(consensus=max(table(unlist(c(var1,var2)))))

This does exactly what I want, but when I try to use a vector of variables i cant get it to work

df %>% 
  rowwise() %>% 
  mutate(consensus=max(unlist(table(select_vars)) )))


Read more here: https://stackoverflow.com/questions/68491293/use-dinamically-generated-column-names-in-dplyr

Content Attribution

This content was originally published by Jorge Kageyama at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: