Personal code snippets of @tmasjc

Image by Mads Schmidt Rasmussen from unsplash.com

Minimal Bootstrap Theme by Zachary Betz

# Map + Reduce in Purrr

Oct 31, 2018 #purrr

Say you have a list which tells you what is y at x. You intend to manipulate y based on certain condition of x.

For example, given

# here x = year, y = some value
(some_list <- list(
"year1" = 60,
"year2" = 70,
"year3" = 75,
"year4" = 80,
"year5" = 100
))
## $year1 ##  60 ## ##$year2
##  70
##
## $year3 ##  75 ## ##$year4
##  80
##
## $year5 ##  100 What is the cumulative sum of y at year 1, 3, 5? In R, it seems natural to do it in a data frame. library(dplyr) # first convert to data frame df <- unlist(some_list) %>% as.data.frame() # assign a column name names(df) <- "y" # calc cumulative sum df %>% mutate(cum_y = cumsum(y)) ## y cum_y ## 1 60 60 ## 2 70 130 ## 3 75 205 ## 4 80 285 ## 5 100 385 There is another convenient way to complete the same job. # what we have some_list ##$year1
##  60
##
## $year2 ##  70 ## ##$year3
##  75
##
## $year4 ##  80 ## ##$year5
##  100
# what we want
cum_x <- c(1, 3, 5)

library(purrr)

# essentially a double loop
map(cum_x, function(x) {
# here 'map' extracts the component from list (x, x, ...)
# and reduce using function 'sum'
reduce(map(1:x, ~ some_list[[.x]]), sum)
})
## []
##  60
##
## []
##  205
##
## []
##  385