Skip to content

Add mapper support for compose #556

@ColinFay

Description

@ColinFay

Issue

Today, if I want to insert mappers in a compose call, I'll have to wrap it into :

sample_round <- compose(
  as_mapper(~ round(.x, 2)),
  mean,
  as_mapper(~ sample(.x, 10))
)
map_dbl(mtcars, sample_round)
   mpg    cyl   disp     hp   drat     wt   qsec     vs     am   gear   carb 
 20.10   6.20 240.62 139.00   3.46   2.92  17.35   0.50   0.40   3.80   2.50 

As this is not supported:

sample_round <- compose(
  ~ round(.x, 2),
  mean,
  ~ sample(.x, 10)
)
Error in FUN(X[[i]], ...) : 
  'list(...)[[1L]]' is not a function, character or symbol

This is because compose uses lapply(list(...), match.fun), and match.fun doesn't know how to deal with formulas.

Proposed solution

I suggest a modification for :

compose <- function(...) {
  fs <- lapply(list(...), as_mapper)
  n <- length(fs)
  
  last <- fs[[n]]
  rest <- fs[-n]
  
  function(...) {
    out <- last(...)
    for (f in rev(rest)) {
      out <- f(out)
    }
    out
  }
}

sample_round <- compose(
  ~ round(.x, 2),
  mean,
  ~ sample(.x, 10)
)
map_dbl(mtcars, sample_round)
   mpg    cyl   disp     hp   drat     wt   qsec     vs     am   gear   carb 
 21.77   5.80 293.78 125.90   3.53   3.27  17.87   0.30   0.70   3.60   2.30 

This would also allow constructing complex "pluckers" :

plop <- list(
  a = list(
    b = list(
      c = list(
        10, 20, 30
        )
    )
  ), 
  aa = list(
    b = list(
      c = list(
        10, 20, 30
      )
    )
  ), 
  aaa = list(
    b = list(
      c = list(
        10, 20, 30
      )
    )
  )
)

plucker <- compose(~ .x * 10, 1, "c", "b")
map(plop, plucker)
$a
[1] 100

$aa
[1] 100

$aaa
[1] 100

Downside

Current version of compose allows to compose with characters elements. I'm not sure if this is widely used though (the documentation do not reference this use case, so I guess we can safely assume this is seldom used):

new_compose <- purrr::compose("round", "mean")
map_dbl(mtcars, new_compose)
 mpg  cyl disp   hp drat   wt qsec   vs   am gear carb 
  20    6  231  147    4    3   18    0    0    4    3 

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions