## Map + Reduce in Purrr

Oct 31, 2018Say 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
## [1] 60
##
## $year2
## [1] 70
##
## $year3
## [1] 75
##
## $year4
## [1] 80
##
## $year5
## [1] 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
## [1] 60
##
## $year2
## [1] 70
##
## $year3
## [1] 75
##
## $year4
## [1] 80
##
## $year5
## [1] 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[1], x[2], ...)
# and reduce using function 'sum'
reduce(map(1:x, ~ some_list[[.x]]), sum)
})
```

```
## [[1]]
## [1] 60
##
## [[2]]
## [1] 205
##
## [[3]]
## [1] 385
```