Pattern for accessing natively-piped element within tidyverse functions?

With {magrittr}, I'd become quite accustomed (and fond of) this pattern:

df %>%
  dplyr::mutate(foo = purrr::pmap(., function(...) {
    do_some_stuff_with(...)
  }))

The 'dot' (.) as the first argument to pmap references df.

With R's base/native pipe (|>), this pattern no longer works. The .data pronoun also doesn't work:

## NO GOOD: . doesn't exist
df |> mutate(foo = pmap(., function(...) do_some_stuff_with(...)))
## NO GOOD: .data is only a pronoun; it doesn't refer to df here
df |> mutate(foo = pmap(.data, function(...) do_some_stuff_with(...)))

The most common way to handle this, as far as I can tell, is with an IIFE:

## SO-SO: works, but the IIFE reduces readability (a lot, IMO)
df |> (\(x) {
  mutate(x, foo = pmap(x, function(...) do_some_stuff_with(...)))
})()

Is there another pattern/utility available within the {tidyverse} that helps replicate the original (more legible) pattern?

The |> equivalent for passing the LHS is

mtcars[which(mtcars$mpg > 20),1] |> sd(x = _)
#> [1] 4.604209

Created on 2023-04-16 with reprex v2.0.2

The "you-gotta-go-home-with-the-one-who-brought-you-to-the-dance" principle suggests sticking with %>% when using {dplyr} and friends or sticking with {base} when using |> is my take.

1 Like

A challenge with _ is it can only be used exactly once in the RHS expression. For {dplyr} mutate()s, that can be limiting when wanting to mutate/create a collection of columns in a single expression.

I hear you re: sticking with {magrittr} for {tidyverse} operations, but the mixing of the two pipes feels very clunky to me. Unavoidable when using one of the 'special' pipes (e.g.%T>%), but in practice 95% of my pipes are the 'standard' variant, and I think mixing them is bad form. This 'use one pipe here but another pipe there' really adds to the challenge of introducing/teaching R to new people :-/.

1 Like

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.