0

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?

Doug Fir
  • 17,940
  • 43
  • 142
  • 263
  • 2
    I'd argue the most "native" way currently is solution 2b in the [linked](https://stackoverflow.com/a/67638063/8107362) answer: e.g. `|> {function(x) grepl("at", x)}()`. Please note the `()` after the anonymous function, since you must call the function, not just define it – mnist Dec 07 '21 at 23:41
  • Be careful with your brackets/braces - `my_mtcars |> (\(x) filter(x, !complete.cases(x)))() |> glimpse()` – thelatemail Dec 07 '21 at 23:46
  • 1
    Perhaps this example may help, it requires setting the environment variable thelatemail mentioned. `1:5 |> (\(.) .*2)() |> x => (\`< z => (\`*\`)(z, 2) * y` – Donald Seinen Dec 08 '21 at 03:15

1 Answers1

3

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(.)
G. Grothendieck
  • 233,926
  • 16
  • 195
  • 321