首页 文章

当你有colnames的字符向量时,如何不使用select()dplyr选择列?

提问于
浏览
5

我试图使用dplyr取消选择我的数据集中的列,但自昨晚以来我无法实现这一点 .

我很清楚工作,但我正在严格尝试通过dplyr找到答案 .

library(dplyr)
df <- tibble(x = c(1,2,3,4), y = c('a','b','c','d'))
df %>% select(-c('x'))

给我一个错误:-c(“x”)出错:一元运算符的参数无效

现在,我知道select接受了不带引号的值,但我无法以这种方式进行子选择 .

请注意上面的数据集只是一个例子,我们可以有很多列 .

谢谢,

Prerit

1 回答

  • 12

    编辑: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 是很奇怪的,其中一个重要的细节就是您不必一直输入引号 . 正如您所看到的,裸值可以与 dplyrggplot2 一起使用 .

相关问题