. vs .x in purrr-style functions with across()

From ?mutate_at:

scale2 <- function(x, na.rm = FALSE) (x - mean(x, na.rm = na.rm)) / sd(x, na.rm)
starwars %>% mutate_at(c("height", "mass"), ~scale2(., na.rm = TRUE))
# ->
starwars %>% mutate(across(c("height", "mass"), ~ scale2(.x, na.rm = TRUE)))

I'm interested in why .x is used with across() but . is still used for the scoped verbs. .x is also used with across() in the colwise article and elsewhere.

In ?map, .x is intended for functions with two arguments, but .y isn't needed or used here. Is the usage of .x more than stylistic? I haven't yet come up with a case which yields different results for .x and . or which causes a naming collision between the . inside the lambda function and the . that is piped into mutate.

I'm aware of the discussion here but I think this question is distinct. Apologies if I have missed something in the documentation that addresses this.

1 Like

As far as I know, .x is the recommended way to refer to single argument functions although . continues to be supported for backward compatibility. The latter is discouraged because it can be easily confused with the . used by %>% (although I have yet to encounter a collision in practice).

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.