Error in dplyr::summarise(mtcars, average = round(mean(column))) :
ℹ In argument: `average = round(mean(column))`.
Caused by error:
! object 'hp' not found
object ‘hp’ not found
we get used to R (and particularly tidyverse) helping us with some sugar when selecting column by their names
mtcars$hp / mtcars |> select(hp)
effectively, we’re just able to specify hp like an object, and R figures out the scope etc for us
that misfires inside functions. R isn’t sure where to look for an object called hp
In some cases, you might find yourself creating a function that’s only going to be used in a single location. In that case, it’s possible to define a nameless (anonymous) function, which is concise-but-nasty. For example:
(\(x)x*2)(5)
[1] 10
Here:
\(x) defines an anonymous function that takes one argument x.
x * 2 is the body of the function which determines how the function works
(5) is the value that we’re supplying to the function
Most usually, that anonymous function won’t be used with a single value, but within a pipe. Here, the supplied value is dropped, and substituted by the values passing along the pipe:
mtcars|>select(wt)|>(\(x)x*2)()|># Double the weight of all the valuesslice_max(wt, n =3)
wt
Lincoln Continental 10.848
Chrysler Imperial 10.690
Cadillac Fleetwood 10.500
Anonymous functions and the magrittr pipe
The magrittr pipe (%>%) has an older, and simple, method of writing anonymous formulas using the . placeholder:
mtcars%>%select(wt)%>%{.*2}%>%# Double the weight of all the valuesslice_max(wt, n =3)
wt
Lincoln Continental 10.848
Chrysler Imperial 10.690
Cadillac Fleetwood 10.500
Resources
best = home made! Refactor something simple in your code today.