Thoughts on internally mapping over a function within itself?



A few weeks ago, I saw an example of someone using purrr::map() within their function to map over that same function. This way, the function can automatically handle vectors of whatever size without the user having to work some map() solution out by themselves.

Do you think this is a good practice to keep? I think it makes sense, and I do it in this function below. See the bottom of the function where I use map_dfr().


get_player_urls <- function(...) {
  .get_player_urls <- function(player_letter, ...) {
    if (tolower(player_letter) == "x") {
      warning("Uh, no X-Men in the NHL. Sorry :/")
    else {
      page <- str_c("", player_letter, "/") %>% read_html()
      player_url <- page %>%
        html_nodes("#div_players a") %>%
        html_attr("href") %>%
        str_c("", .) %>%
        as_tibble() %>%
      player_name <- page %>%
        html_nodes("#div_players a") %>%
        html_text() %>%
        as_tibble() %>%
      player_data <- bind_cols(player_name, player_url)
  all_player_data <- map_dfr(..., .get_player_urls)


That sounds like it risks infinite loops.

But this is just fine, loop-wise. It's a good practice to explicitly define and name a non-trivial function for mapping, so cheers.

I do suggest replacing the "..." argument with a single variable, since anything beyond the first argument has no use in the code.


Thanks for the response, @nwerth (and sorry for not responding sooner).

Just curious,

What do you mean by this?