Home > Blockchain >  R - how to use the exposition pipe %$% in purrr::map
R - how to use the exposition pipe %$% in purrr::map

Time:09-30

For the purposes of this question, let's split the mtcars dataset into several smaller ones, for example based on carb and store them all in a list

mtlist <- group_split(mtcars, carb)

Let's now say that, only on one of these datasets, I am operating some pipeline and in the end I want to select a single variable using the exposition operator %$%:

mtlist[[1]] %>% 
mutate(cyl = 6*cyl) %$%
cyl

Output:

24 36 36 24 24 24 24

However, what if I wish to do so on the whole mtlist? The following doesn't work:

mtlist %>% 
  map(mutate, cyl = 6*cyl) %$%
  cyl

So what would be the way to do it?

I know that I can achieve the same final output in other ways, e.g. map(select, cyl), but I am looking to learn how to do it specifically with the exposition pipe %$%.

CodePudding user response:

If you look at the documentation of %$%, it says that:

[%$%] [e]xpose the names in lhs to the rhs expression. This is useful when functions do not have a built-in data argument.

In your case the names of the lhs are the names of the list, so you cannot really use cyl directly. You have to do it inside a map call:

library(magrittr)
library(purrr)
library(dplyr)

mtlist %>% 
  map(mutate, cyl = 6*cyl) %>%
  map(~ .x %$% cyl)

returning

[[1]]
[1] 24 36 36 24 24 24 24

[[2]]
 [1] 48 24 24 24 48 48 48 24 24 24

[[3]]
[1] 48 48 48

[[4]]
 [1] 36 36 48 36 36 48 48 48 48 48

[[5]]
[1] 36

[[6]]
[1] 48
  • Related