Extracting information from the dataset

Intermediate Functional Programming with purrr

Colin Fay

Data Scientist & R Hacker @ ThinkR

Function manipulation

We've seen:

  • partial()

  • compose()

Intermediate Functional Programming with purrr

partial()

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
Intermediate Functional Programming with purrr

compose()

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
Intermediate Functional Programming with purrr

Cleaner lists

Removing NULL:

  • compact()

Removing one level:

  • flatten()
Intermediate Functional Programming with purrr

compact()

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
Intermediate Functional Programming with purrr

flatten()

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

Let's practice!

Intermediate Functional Programming with purrr

Preparing Video For Download...