across inside mutate warning

This is not reproducible because my dataset is really large to post here. I am getting a warning that
I don’t understand when using across inside mutate on the line of code below:

mort %>% mutate(across(lifestage, factor, levels=c("larvae","adult", "postlarvae")))
There was 1 warning in `mutate()`.
i In argument: `across(lifestage, factor, levels = c("larvae", "adult", "postlarvae"))`.
Caused by warning:
! The `...` argument of `across()` is deprecated as of dplyr 1.1.0.
Supply arguments directly to `.fns` through an anonymous function instead.

  # Previously
  across(a:b, mean, na.rm = TRUE)

  # Now
  across(a:b, \(x) mean(x, na.rm = TRUE))
This warning is displayed once every 8 hours.

Question: How can I organize levels like so below using the new way across/mutate works?

mort %>% 
  mutate(across(lifestage, factor, 

>Solution :

The error is one of the best in R: it tells you where is wrong, what is wrong about it, and even offers template code to use to correct the issue. The issue is not that you offer mean by itself, it’s that the levels=... argument is matched within across‘s ... catch-all arguments. The current behavior of across will pass the ... arguments to the function.

Personally, I like the use of ..., but there are times when it can be ambiguous, such as when you pass both an anonymous function (not a named one) and args to the dots. Many times it will just work, but … the dplyr authors are recommending against this, and have made it into this warning. (I wouldn’t be surprised if it turns into an error at some point, as part of slow lifecycle management.)

You can choose from among these:

# using rlang's "~" quasi-function
mutate(across(lifestage, ~ factor(., levels=c("larvae", "adult", "postlarvae"))))

# using R's basic anonymous function
mutate(across(lifestage, function(z) factor(z, levels=c("larvae", "adult", "postlarvae"))))

# using R-4's new abbreviated anonymous function
mutate(across(lifestage, \(z) factor(z, levels=c("larvae", "adult", "postlarvae"))))

with equal effect.

Leave a Reply