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:
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 themagrittr
pipe%>%
, but not the base pipe|>
.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 therhs
call to specify where thelhs
is to be inserted. The placeholder can only appear once on therhs
.
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
# ...