Home > front end >  promise already under evaluation with nesting from function
promise already under evaluation with nesting from function

Time:10-10

Following on from my previous exericse: Store dplyr method in function and return outside, I wanted a complex challenge to involve multiple functions within a dplyr method. This challenge applies an additional nest from a function to outside the function. However, I get this error:

promise already under evaluation: recursive default argument reference or earlier problems?

Here is what I have tried:

nestLoop <- function(dframe, main, sub = NULL, ...) {
  cols <- enquos(...)
  
  outerNest <- dframe %>% nest_by({{main}})
  
  repeatNest <- function(df, col) {
    df %>% mutate(data = map(data, ~ .x %>% nest(data = -!!!col)))
  } 
    nested <-
      outerNest %>% ungroup %>% mutate(data = map(data, ~ .x %>% nest(data = -{{sub}}) %>% repeatNest(., cols)))
  nested
}
nestLoop(mtcars, vs, am, gear)

CodePudding user response:

The issue is that you have to wrap !!!col in c():

library(dplyr, warn=FALSE)
library(tidyr)
library(purrr)

nestLoop <- function(dframe, main, sub = NULL, ...) {
  cols <- enquos(...)
  
  outerNest <- dframe %>% 
    nest_by({{main}}) %>%
    ungroup()
  
  repeatNest <- function(df, col) {
    df %>% 
      mutate(data = map(data, ~ .x %>% nest(data = -c(!!!col))))
  } 
  
  nested <- outerNest %>% 
    mutate(data = map(data, ~ .x %>% nest(data = -{{sub}}) %>% repeatNest(., cols)))
  
  nested
}

nestLoop(mtcars, vs, am, gear)
#> # A tibble: 2 × 2
#>      vs data            
#>   <dbl> <list>          
#> 1     0 <tibble [2 × 2]>
#> 2     1 <tibble [2 × 2]>
  • Related