整洁选择(tidyselect)如何在R中的选择函数中引用外部变量名向量

8

我在使用 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)

提供:

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.

如果我进行重构并变更代码为以下形式,它将不会发出警告:

df.selected = df %>% 
  dplyr::select(total, all_of(cols.to.sum))

这种行为从 tidyselect_0.2.5 更改为 tidyselect_1.0.0。直到现在还没有任何警告。

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

我的问题是如何处理现有代码中的这种更改。

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

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

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

谢谢


这个问题可能更适合在这个github讨论中提出。 - Prashant Bharadwaj
1个回答

1
如果你的第一个问题中“should”是操作短语,那么只需要确保没有将任何变量命名为“cols.to.sum”。只要这样做了,使用“all_of()”的属性就与你的用例无关,可以像往常一样继续使用“select”。
如果你不想坚持使用旧版本的“tidyselect”,suppress library可能会有所帮助。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接