I would like to understand whether and how to do this using the tidyverse framework.
Suppose I have the following simple function:
my_fn <- function(list_char) { data.frame(comma_separated = rep(paste0(list_char, collapse = ","),2), second_col = "test", stringsAsFactors = FALSE) }
Given the list below:
list_char <- list(name = "Chris", city = "London", language = "R")
my function works fine if you run:
my_fn(list_char)
However, if we change some list elements with a character vector, we could use the dplyr::do function as follows:
list_char_mult <- list(name = c("Chris", "Mike"), city = c("New York", "London"), language = "R") expand.grid(list_char_mult, stringsAsFactors = FALSE) %>% tbl_df() %>% group_by_all() %>% do(my_fn(list(name = .$name, city = .$city, language = "R")))
The question is how to write a function that could do this for a list with a variable number of elements. For instance:
my_fn_generic <- function(list_char_mult) { expand.grid(list_char_mult, stringsAsFactors = FALSE) %>% tbl_df() %>% group_by_all() %>% do(my_fn(...)) }
thanks
source share