from for-loops to purrr: named sublist assignment

I am finally trying to make the jump from for-loops to purrr. The basic examples are quite intuitive enough, but translating for-loops has been tricky, especially when trying to assign output objects to lists. Consider the following example where I am trying to assign the output of a nested for-loop to a named list element.

library(tidyverse)

# output list
loop_list <- list()

# iterate over colors
for (color in diamonds %>% distinct(color) %>% pull()){
  
  # sublist for each color
  loop_list[[color]] <- list()
  
  # iterate over cuts
  for(cut in diamonds %>% distinct(cut) %>% pull()){
    
    # filter data
    data <- diamonds %>% 
      filter(color == color & cut == cut)
    
    # define output
    out <- data %>% 
      pull(price) %>% 
      mean()
    
    # assign output to sublist of its color
    loop_list[[color]][[cut]] <- out
    
    # clean up filtered data set
    rm(data)
  }
}

This nested loop assigns the output object to its properly named sublist for each color of the data set. My purrr attempt creates something similar, but without the named sublists. All output objects are assigned to the same list, which is not what I'd ideally like.

grid <- expand_grid(color = diamonds %>% distinct(color) %>% pull(),
                    cut = diamonds %>% distinct(cut) %>% pull())

myfunc <- function(data, color, cut){
  
  # create output object
  out <- data %>% 
    # filter data
    filter(color == color & cut == cut) %>%  
    pull(price) %>% 
    mean()
  
  # return output
  return(out)
}

purrr_list <- grid %>%
  pmap(myfunc, data = diamonds)

Is there a way to arrive at the same output with purrr? I am aware that global assignment with <<- is a possibility, but this is generally discouraged, from what I understand.



from Recent Questions - Stack Overflow https://ift.tt/3moxCH3
https://ift.tt/eA8V8J

Comments

Popular posts from this blog

Today Walkin 14th-Sept

Hibernate Search - Elasticsearch with JSON manipulation

Spring Elasticsearch Operations