I am trying to pass two sets of column names to function and do something with them using dplyr. Normally for one set I would use the ellipsis (...) and convert it to quosures with enquos(). But now I have two sets of column names so I thought about using lists to store them. How should I make this work in the most efficient way? (Answers using purrr, rlang and any other packages' functions are most welcome)
Packages and example of data
library(dplyr) #I use whole library(tidyverse) but this is sufficient for this case
some.data <- tibble(col1 = sample(letters[1:3], 500, replace = T),
col2 = sample(letters[1:3], 500, replace = T),
col3 = sample(letters[4:6], 500, replace = T),
col4 = sample(letters[4:6], 500, replace = T))
My function (put simple) looks like this:
cross_table <- function(data = NULL, list1 = NULL, list2 = NULL){
for(l1 in list1){
for(l2 in list2){
data.out <- data %>%
count(l1, l2) %>%
spread(l2, n, fill = 0, drop = FALSE)
print(data.out) #Just to show it works. I want to use 'data.out' object later on
}
}
}
and I want to use function like this (not giving columns' names as strings)
some.data %>%
cross_table(list1 = list(col1, col2), list2 = list(col3, col4))