Intermediate Functional Programming with purrr
Colin Fay
Data Scientist & R Hacker @ ThinkR
We've seen:
partial()
compose()
partial()
prefills a function:
sum_no_na <- partial(sum, na.rm = TRUE)
map_dbl(airquality, sum_no_na)
Ozone Solar.R Wind Temp Month Day
4887.0 27146.0 1523.5 11916.0 1070.0 2418.0
compose()
a function:
rounded_sum <- compose(round, sum_no_na)
map_dbl(airquality, rounded_sum)
Ozone Solar.R Wind Temp Month Day
4887 27146 1524 11916 1070 2418
Removing NULL
:
compact()
Removing one level:
flatten()
l <- list(NULL, 1, 2, 3, NULL)
l
[[1]]
NULL
[[2]]
[1] 1
[[3]]
[1] 2
[[4]]
[1] 3
[[5]]
NULL
l <- list(NULL, 1, 2, 3, NULL)
compact(l)
[[1]]
[1] 1
[[2]]
[1] 2
[[3]]
[1] 3
my_list <- list(
list(a = 1),
list(b = 2)
)
my_list
[[1]]
[[1]]$a
[1] 1
[[2]]
[[2]]$b
[1] 2
my_list <- list(
list(a = 1),
list(b = 2)
)
flatten(my_list)
$a
[1] 1
$b
[1] 2
Intermediate Functional Programming with purrr