Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

R – how to use the exposition pipe %$% in purrr::map

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 %$%.

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading