Home > OS >  New pipe placeholder _ inside mutate (transform) function
New pipe placeholder _ inside mutate (transform) function

Time:08-24

Can someone explain to me how to call the new pipe placeholder _ inside a function, inside mutate? Here is a silly example:

library(dplyr)
iris |>
  mutate(n_rows = nrow(x = _))
Error in mutate(iris, n_rows = nrow(x = "_")) : 
  invalid use of pipe placeholder

CodePudding user response:

The native pipe placeholder _ cannot be used in nested calls, that is why you are getting this error.

You could something like this to make it work:

iris |>
  nrow() |>
  transform(iris, x = _)

CodePudding user response:

You can't for 2 reasons:

  1. The base pipe can only pipe to one argument. In your example, you need the data frame to appear twice: mutate(iris, n_rows = nrow(iris)). This is possible with the magrittr pipe %>%, but not the base pipe |>.

  2. As Maël says, you can't use _ in a nested function call.

From the R Release News announcing _:

In a forward pipe |> expression it is now possible to use a named argument with the placeholder _ in the rhs call to specify where the lhs is to be inserted. The placeholder can only appear once on the rhs.

CodePudding user response:

You may use an anonymous function instead; gives the intended transformed data frame.

iris |>
  {\(.) transform(., n_rows=nrow(x=.))}()

or

iris |>
  {\(.) dplyr::mutate(., n_rows=nrow(x=.))}()

#     Sepal.Length Sepal.Width Petal.Length Petal.Width    Species n_rows
# 1            5.1         3.5          1.4         0.2     setosa    150
# 2            4.9         3.0          1.4         0.2     setosa    150
# 3            4.7         3.2          1.3         0.2     setosa    150
# ...
  • Related