R语言 跨越内部变异警告

xqnpmsa8  于 2023-09-27  发布在  其他
关注(0)|答案(1)|浏览(98)

这是不可复制的,因为我的数据集非常大,无法在这里发布。在下面的代码行中使用across inside mutate时,我得到了一个警告,我不明白:

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.

问:我如何使用新的跨/突变工作方式来组织下面的级别?

mort %>% 
  mutate(across(lifestage, factor, 
                levels=c("postlarvae","larvae","adult")))
xmq68pz9

xmq68pz91#

错误是R中最好的错误之一:它会告诉你哪里出了问题,哪里出了问题,甚至还提供了用来纠正问题的模板代码。问题不在于您单独提供了mean,而是levels=...参数在across...捕获所有参数中匹配。across的当前行为将把...参数传递给函数。
就我个人而言,我喜欢使用...,但有时它可能是模糊的,例如当您同时传递匿名函数(而不是命名函数)和args时。很多时候它只是工作,但是... dplyr的作者建议不要这样做,并将其写入了此警告中。(如果它在某个时候变成一个错误,作为缓慢的生命周期管理的一部分,我不会感到惊讶。
您可以从以下选项中进行选择:

# 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"))))

具有相同的效果。

相关问题