编辑:OP 的实际问题是关于如何使用字符向量从数据框中选择或取消选择列。为此使用one_of() 辅助函数:
colnames(iris)
# [1] "Sepal.Length" "Sepal.Width" "Petal.Length" "Petal.Width" "Species"
cols <- c("Petal.Length", "Sepal.Length")
select(iris, one_of(cols)) %>% colnames
# [1] "Petal.Length" "Sepal.Length"
select(iris, -one_of(cols)) %>% colnames
# [1] "Sepal.Width" "Petal.Width" "Species"
您应该看看选择助手(输入?select_helpers),因为它们非常有用。来自文档:
starts_with():以前缀开头
ends_with():以前缀结尾
contains(): 包含一个文字字符串
matches():匹配正则表达式
num_range():一个数字范围,如 x01、x02、x03。
one_of(): 字符向量中的变量。
everything():所有变量。
给定一个列名为 a:z 的数据框,像这样使用 select:
select(-a, -b, -c, -d, -e)
# OR
select(-c(a, b, c, d, e))
# OR
select(-(a:e))
# OR if you want to keep b
select(-a, -(c:e))
# OR a different way to keep b, by just putting it back in
select(-(a:e), b)
因此,如果我想省略 iris 数据集中的两列,我可以说:
colnames(iris)
# [1] "Sepal.Length" "Sepal.Width" "Petal.Length" "Petal.Width" "Species"
select(iris, -c(Sepal.Length, Petal.Length)) %>% colnames()
# [1] "Sepal.Width" "Petal.Width" "Species"
当然,实现这一目标的最佳和最简洁的方法是使用select 的辅助函数之一:
select(iris, -ends_with(".Length")) %>% colnames()
# [1] "Sepal.Width" "Petal.Width" "Species"
附:将引用的值传递给dplyr 很奇怪,它的一大优点是您不必 必须一直输入引号。如您所见,裸值适用于 dplyr 和 ggplot2。