【问题标题】:select columns that do NOT start with a string using dplyr in R在 R 中使用 dplyr 选择不以字符串开头的列
【发布时间】:2020-01-03 22:39:21
【问题描述】:

我想从 tibble 中选择以字母 R 结尾且不以字符串 ("hc") 开头的列。例如,如果我有一个如下所示的数据框:

name  hc_1  hc_2  hc_3r  hc_4r  lw_1r  lw_2  lw_3r  lw_4   
Joe   1     2     3      2      1      5     2      2
Barb  5     4     3      3      2      3     3      1

为了做我想做的事,我尝试了很多选择,但我很惊讶这个不起作用:

library(tidyverse)
data %>%
  select(ends_with("r"), !starts_with("hc"))

当我尝试时,我得到了这个错误:

错误:!starts_with("hc") 必须计算为列位置或名称,而不是逻辑向量

我也尝试过使用 negate() 并得到同样的错误。

library(tidyverse)
data %>%
  select(ends_with("r"), negate(starts_with("hc")))

错误:negate(starts_with("hc")) 必须计算为列位置或名称,而不是函数

我想将答案保留在 dplyr select 函数中,因为一旦我选择了变量,我最终会使用 mutate_at 来反转它们,所以最好是一个整洁的解决方案。

谢谢!

【问题讨论】:

    标签: r select dplyr startswith negate


    【解决方案1】:

    我们可以使用-,因为starts_with 输出不是逻辑向量

    library(dplyr)
    data %>%
         select(ends_with("r"), -starts_with("hc"))
     #   lw_1r lw_3r
     #1     1     2
     #2     2     3
    

    数据

    data <- structure(list(name = c("Joe", "Barb"), hc_1 = c(1L, 5L), hc_2 = c(2L, 
    4L), hc_3r = c(3L, 3L), hc_4r = 2:3, lw_1r = 1:2, lw_2 = c(5L, 
    3L), lw_3r = 2:3, lw_4 = 2:1), class = "data.frame", row.names = c(NA, 
    -2L))
    

    【讨论】:

    • 谢谢!但是假设我有另一组以 jw_1、jw_2r 等开头的列。那我怎么能说我只想要以 lw 开头和以 r 结尾的列?有没有办法将需求联系在一起?
    • 如果你走的是starts_with/end_with路线,你可以使用另一组-starts_with("jw"),因为这只能是一个模式。否则你可能不得不使用matches,就像另一个答案matches("^lw.*r$")
    • 好的,谢谢!我希望我可以在 select 命令中添加一个 & 语句,但我想这是不可能的。谢谢!
    【解决方案2】:

    如果您需要高级正则表达式,请使用 matches

    library(dplyr)
    #Starts with any letter except h or c and ends with an r
    df %>% select(matches('^[^hc].*r$'))
      lw_1r lw_3r
    1     1     2
    2     2     3
    

    【讨论】:

      猜你喜欢
      • 2022-12-24
      • 1970-01-01
      • 2018-08-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-25
      相关资源
      最近更新 更多