Generate a name for an element in a list. This function is targeted for
functions creations which handle lists. Those lists may need names to go
through each elements. This function can works with stats::setNames()
and
allows the user to provide name shorter, more user-friendly in their lists.
make_name_list(args_list, list_elem)
A list of character string of same length of list_elem
A list of character string of same length of args_list
A character string simplified to be used as names in a list.
{
library(tidyr)
library(stats)
#### Example 1 --------------------------------------------------------------
# make_name_list generates names that are informative through a line of code
# or function. tibble(iris), iris %>% tibble and
# list(iris = tibble(mytibble) %>% select(Species)) will have 'iris' as name.
list(tibble(iris), tibble(mtcars)) %>%
setNames(make_name_list(list(tibble(iris), tibble(mtcars)), args_list =
c("IRIS %>% complicated_code","complicated_function(MTCARS)")))
#### Example 2 --------------------------------------------------------------
# make_name_list can be used when a function uses arguments provided by the
# user to generate a list. The name is simplified and given to the list
# itself
library(dplyr)
my_function <- function(df){
.fargs <- as.list(match.call(expand.dots = TRUE))
list_df <-
list(df) %>%
setNames(.,make_name_list(as.character(.fargs['df']),list(df)))
return(list_df)}
my_function(tibble(iris))
my_function(iris %>% tibble %>% select(Species))
}
#> $iris
#> # A tibble: 150 × 1
#> Species
#> <fct>
#> 1 setosa
#> 2 setosa
#> 3 setosa
#> 4 setosa
#> 5 setosa
#> 6 setosa
#> 7 setosa
#> 8 setosa
#> 9 setosa
#> 10 setosa
#> # ℹ 140 more rows
#>