Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Native pipe placeholder [duplicate]

Tags:

r

I realize this question has been asked before but it's not clicking. There's really no placeholder?

Example:

my_mtcars <- mtcars %>% mutate(bla = c(1:nrow(.)))
my_mtcars$bla[10] <- NA
my_mtcars$bla[15] <- NA

Works:

# magritr pipe to return NA rows while debugging a df
my_mtcars %>% filter(!complete.cases(.)) %>% glimpse

Does not work:

# native piple equivilent
my_mtcars |> filter(!complete.cases(.)) |> glimpse()

What's the 'right' way to do what I'm trying to do with the native pipe?

like image 759
Doug Fir Avatar asked Sep 19 '25 23:09

Doug Fir


1 Answers

The native R pipe does not use dot. It always inserts into the first argument. To get the effect of dot define a function or if it is at the beginning combine it yourself repeating the input (or break it up into two pipelines and do the same -- not shown since doesn't apply here).

library(dplyr)

mtcars |>
  (\(x) filter(x, complete.cases(x)))() |>
  summary()

or

f <- function(x) filter(x, complete.cases(x))
mtcars |> f() |> summary()

or

filter(mtcars, complete.cases(mtcars)) |> summary()

Sometimes with can be used to create a workaround. This creates a list with one element named x and then uses that in the next leg of the pipe.

mtcars |>
  list() |>
  setNames("x") |>
  with(filter(x, complete.cases(x))) |>
  summary()

Note that you can do this with only base R -- the Bizarro pipe which is not really a pipe but looks like one.

mtcars ->.;
  filter(., complete.cases(.)) ->.;
  summary(.)

Update

Since this question appeared R has added a _ placeholder so the with example could be shortened to:

# needs R 4.2 or later
mtcars |>
  list(x = _) |>
  with(filter(x, complete.cases(x))) |>
  summary()
like image 120
G. Grothendieck Avatar answered Sep 22 '25 12:09

G. Grothendieck