在R中使用dplyr选择不以字符串开头的列

J.S*_*ree 3 select r startswith negate dplyr

我想从小标题中选择以字母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
Run Code Online (Sandbox Code Playgroud)

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

library(tidyverse)
data %>%
  select(ends_with("r"), !starts_with("hc"))
Run Code Online (Sandbox Code Playgroud)

尝试时,出现以下错误:

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

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

library(tidyverse)
data %>%
  select(ends_with("r"), negate(starts_with("hc")))
Run Code Online (Sandbox Code Playgroud)

错误:negate(starts_with("hc"))必须求值到列的位置或名称,而不是函数

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

谢谢!

akr*_*run 6

我们可以使用-作为starts_with输出不是一个逻辑向量

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

数据

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))
Run Code Online (Sandbox Code Playgroud)


A. *_*man 5

如果您需要高级正则表达式,请使用 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
Run Code Online (Sandbox Code Playgroud)