我有这样的数据:
df <- data.frame(name = c("James", "jonathan", "Abel", "Cynthia", "Cornelius", "alex"))
name
James
jonathan
Abel
Cynthia
Cornelius
alex
我想选择
name
不以“A”或“J”开头的行。预期结果:
name
Cynthia
Cornelius
我想要一个简单的
dplyr
解决方案。
您可以将
grepl
与 filter
一起使用:
df |>
filter(!grepl("^[A|J]", name, ignore.case = TRUE))
dplyr
没有任何特殊的字符串函数。您只想使用 filter
进行测试,看看第一个字母是否不是 A 或 J。这里有一种方法,将 name
转换为大写以进行测试,使用 substr
提取第一个字符,然后然后测试它是否不是 J 或 A:
library(dplyr)
df |>
filter(!substr(toupper(name), 1, 1) %in% c("J", "A"))
您可以通过多种其他方式编写测试,从基础使用
grepl
或 startsWith
,使用 stringr::str_detect
或 stringi::stri_detect
等。
在基础 R 中,您可以使用
grep
进行索引(使用 invert = TRUE
和 ignore.case = TRUE
):
df[grep("^A|^J", df$name, invert = TRUE, ignore.case = TRUE),]
#[1] "Cynthia" "Cornelius"