R:将向量变量用于 select 列时收集会发出警告

R: gather gives warning when using vector variable to select columns

我在 R 中使用 gather 命令折叠数据框,它给出了我不清楚的警告。该命令执行了它应该执行的操作,但我想了解发出警告的原因。这是一个新警告,可能与最近更新 R 安装和软件包有关。

我在一个简单的例子中用虹膜数据重现了这个问题,见下文,它在列号 2,3 的情况下没有警告,但如果我使用我创建为 tt 的向量时会发出警告:

> head(gather(iris,key=test,value=nn,2,3),2)
    Sepal.Length Petal.Width   Species         test  nn
299          6.2         2.3 virginica Petal.Length 5.4
300          5.9         1.8 virginica Petal.Length 5.1
> tt<- c(2,3)
> head(gather(iris,key=test,value=nn,tt),2)
    Sepal.Length Petal.Width   Species         test  nn
299          6.2         2.3 virginica Petal.Length 5.4
300          5.9         1.8 virginica Petal.Length 5.1
Warning message:
In if (!is.finite(x)) return(FALSE) :
  the condition has length > 1 and only the first element will be used

谢谢,克劳迪乌

最好使用 names 而不是位置,因为删除或添加列时位置可能会发生变化。由于 'tt' 是一个数字索引,我们可以使用它来对列名

进行子集化
library(dplyr)
library(tidyr)
library(quantmod)
last(gather(iris,key=test,value=nn, names(iris)[tt]),2)
#    Sepal.Length Petal.Width   Species         test  nn
#299          6.2         2.3 virginica Petal.Length 5.4
#300          5.9         1.8 virginica Petal.Length 5.1