使用带有 OR 条件的 grepl 来过滤字符串

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

目前我有一个像这样的 df:

df <- data.frame(
  player = c('Player To Have 1 Or More Shots On Target', 'Player To Have 1 Or More Shots On Target', 
             'Player To Have 2 Or More Shots On Target', 'Player To Have 3 Or More Shots On Target',
             'Player To Have 1 Or More Shots On Target in 1st Half'))

输出:

                                                player
1             Player To Have 1 Or More Shots On Target
2             Player To Have 1 Or More Shots On Target
3             Player To Have 2 Or More Shots On Target
4             Player To Have 3 Or More Shots On Target
5 Player To Have 1 Or More Shots On Target in 1st Half

我想使用 grepl (或其他合适的替代方案)仅捕获目标上的 1,2,3,4 等镜头(忽略其他任何内容,例如第 5 行也包含 'in 1st Half)。

在上面的示例中,我希望捕获所有前 4 行(原始数据还有更多行)。我尝试了以下有效的方法:

df2 <- dplyr::filter(df, grepl("Player To Have 1 Or More Shots On Target", player))

如何修改上述内容以包含多个数字“1”?例如。我想拍摄 1、2、3、4 等镜头?

我尝试过类似的事情:

number_of_shots <- c("1","2")
df2 <- dplyr::filter(df, grepl("Player To Have", number_of_shots, "Or More Shots On Target", player))

但是我收到以下错误:

Error in `dplyr::filter()`:
ℹ In argument: `grepl(...)`.
Caused by error:
! `..1` must be of size 5 or 1, not size 2.
r dplyr grepl
1个回答
0
投票

可以使用正则表达式

  • ^
    开头并以
    $
    匹配结束
  • [0-9]
    匹配 0-9 中的任何数字,
    [1-4]
    如果您只想匹配 1 到 4。使用
    .*
    匹配任何数字。

df <- data.frame(
  player = c('Player To Have 1 Or More Shots On Target', 'Player To Have 1 Or More Shots On Target', 
             'Player To Have 10 Or More Shots On Target', 'Player To Have 3 Or More Shots On Target',
             'Player To Have 1 Or More Shots On Target in 1st Half'))

# match 0-9
df %>%
  filter(grepl('^Player To Have [0-9] Or More Shots On Target$', player))

# match anything 
df %>%
  filter(grepl('^Player To Have .* Or More Shots On Target$', player))
© www.soinside.com 2019 - 2024. All rights reserved.