使用标准评估选择可能不存在错误的列

时间:2018-10-01 22:32:47

标签: r tidyverse

我想选择一个可能存在或可能不存在的列,如果该列丢失而没有错误,则让它简单地返回所有其他列。这适用于非标准评估,但不适用于带有tidyverse函数select_的标准评估。

例如,以下功能可以正常工作:

iris %>%
  select(Sepal.Length, Sepal.Width, contains("banana"))

    Sepal.Length Sepal.Width
1            5.1         3.5
2            4.9         3.0
3            4.7         3.2
4            4.6         3.1
...

但是使用标准评估(我需要使用该评估将其发布到程序包中)无法正常工作:

iris %>%
  select_("Sepal.Length", "Sepal.Width", contains("banana"))

Error: No tidyselect variables were registered

我意识到该版本中断了什么,但是我不确定使用tidyverse功能有哪些替代方案。

1 个答案:

答案 0 :(得分:3)

如果您愿意离开tidyverse,则可以对列名进行显式操作:

iris[intersect(names(iris), c("Sepal.Length","Sepal.Width","banana"))]

对于contains(),您可以使用grep

ccols <- c("Sepal.Length", "Sepal.Width", 
           grep("banana", names(iris), value=TRUE))
iris[ccols]

如果您将字符串替换为变量引用(即:

),这仍然会起作用(因为它是 standard 评估)
x <- "banana"
ccols <- c("Sepal.Length", "Sepal.Width", 
           grep(x, names(iris), value=TRUE))
iris[ccols]