tidyselect 更改了在 R 中选择函数时如何引用变量名称的外部向量

alv*_*opr 7 r tidyverse tidyselect

tidyverse包中使用选择功能时,我开始收到警告。

例子:

library(dplyr)
set.seed(123)
df = data.frame(
  "id" = c(rep("G1", 3), rep("G2", 4), rep("G3", 3)),
  "total" = sample.int(n = 10),
  "C1" = sample.int(n=10),
  "C2" = sample.int(n=10),
  "C3" = sample.int(n=10))
cols.to.sum = c("C1", "C2")
df.selected = df %>% 
  dplyr::select(total, cols.to.sum)
Run Code Online (Sandbox Code Playgroud)

给予:

Note: Using an external vector in selections is ambiguous.
i Use `all_of(cols.to.sum)` instead of `cols.to.sum` to silence this message.
i See <https://tidyselect.r-lib.org/reference/faq-external-vector.html>.
This message is displayed once per session.
Run Code Online (Sandbox Code Playgroud)

如果我重构为:

df.selected = df %>% 
  dplyr::select(total, all_of(cols.to.sum))
Run Code Online (Sandbox Code Playgroud)

此行为已从 更改tidyselect_0.2.5tidyselect_1.0.0。直到现在都没有警告。

在有关此更改的文档 ( https://tidyselect.r-lib.org/reference/faq-external-vector.html ) 中,声明这只是一个警告,但将来会变成错误。

我的问题是如何处理有关现有代码的此类更改。

我是否应该重构使用此选择方法添加all_of()到外部向量引用的每一行代码?当代码中可能有数百个片段以这种方式进行选择时,这听起来很难完成(它也会影响其他功能 summarise_at,例如)。

唯一的选择是坚持tidyselect_0.2.5保持运行代码正常工作吗?

在关于现有代码的包中进行这样的更改的方法是什么?

谢谢

小智 1

如果“应该”是您第一个问题中的操作短语,那么这可能只是确保您的变量没有被命名的问题cols.to.sum。只要是这种情况,using 的属性all_of()就不会与您的用例相关,您可以select照常进行。

如果您不想坚持使用旧版本的抑制库tidyselect可能会有所帮助