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?
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(.)
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With