如何在 R 中选择以特定字符串开头的行?

问题描述 投票:0回答:3

我有这样的数据:

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
解决方案。

r variables dplyr tidyverse data-cleaning
3个回答
1
投票

您可以将

grepl
filter
一起使用:

df |>
  filter(!grepl("^[A|J]", name, ignore.case = TRUE))

0
投票

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
等。


0
投票

在基础 R 中,您可以使用

grep
进行索引(使用
invert = TRUE
ignore.case = TRUE
):

df[grep("^A|^J", df$name, invert = TRUE, ignore.case = TRUE),]

#[1] "Cynthia"   "Cornelius"
© www.soinside.com 2019 - 2024. All rights reserved.