目前我的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 first Half").

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

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

如何才能省略上述字符,使其包含多个数字"1"?例如,我想拍摄1、2、3、4等镜头?

我try 了一些类似的方法:

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.

推荐答案

可以使用正则表达式

  • ^开始,以$匹配结束
  • 如果要匹配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))

R相关问答推荐

在R中列表的结尾添加数字载体

从嵌套列表中智能提取线性模型系数

行式dppr中的变量列名

如何使用rmarkdown和kableExtra删除包含折叠行的表的第一列的名称

如何求解arg必须为NULL或deSolve包的ode函数中的字符向量错误

用derrr在R中查找组间的重复项

如何在编辑列时更新可编辑数据表,并使用该表在Shiny中执行连续计算

如何在modelsummary中重命名统计数据?

计算具有奇数日期的运行金额

R根据条件进行累积更改

Ggplot2中的重复注记

在ggplot中为不同几何体使用不同的 colored颜色 比例

DEN扩展包中的RECT树形图出现异常行为

如何根据R中其他变量的类别汇总值?

来自程序包AFEX和amp;的类/函数和NICE_TABLE&冲突

如何创建累加到现有列累计和的新列?

判断函数未加载R中的库

计算Mean by分组和绑定到R中的数据集

使用ggplot2绘制具有边缘分布的坡度图

使用nls()函数的非线性模型的半正态图