在 R 中用一个特定的字符串值过滤行

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

我在 R 中有一个数据框,如下所示:

Fruits
Apple:1
Apple:4
Bananna    
Papaya    
Orange, Apple:2

我想过滤字符串为 Apple 的行

Apple:1
Apple:4 

我尝试使用 dplyr 包。

df <- dplyr::filter(df, grepl('Apple', Fruits))

但它过滤带有字符串 Apple 的行为:

Apple:1
Apple: 4     
Orange, Apple:2

如何删除包含多个字符串的行并过滤包含一个特定字符串的行(在本例中为 Apple)?

r dataframe dplyr filtering stringr
1个回答
1
投票

要仅过滤掉

Apple
,您可以使用正则表达式锚点
^
指定字符串的开头,后跟“Apple:”和任何数字。最后用
$
结束搜索模式,它指定字符串的结尾。如果字符串之间有任何其他字符,搜索将返回
FALSE

library(dplyr)

df %>% filter(grepl("^Apple:\\d+$", Fruits))

   Fruits
1 Apple:1
2 Apple:4
© www.soinside.com 2019 - 2024. All rights reserved.