【问题标题】:Filter entries that start with string (str_detect)过滤以字符串开头的条目 (str_detect)
【发布时间】:2019-01-22 05:36:49
【问题描述】:

过滤以字符串开头的条目

library(tidyverse)

假数据

Code <- c("a", "b", "c", "d", "e", "f")
Info <- c("test", "shop for test", "test", "shop group for test", "test", "test shop for test")
dd <- data.frame(Code, Info)
rm(Code, Info)

期望的输出

代码尝试

tt <- dd %>%
  filter(str_detect(Info, "^shop for | shop group for")) #it should generate two entries

【问题讨论】:

  • 始终建议在您的帖子中使用代码标签添加输入示例和输出示例,请这样做。
  • 问题是 (| ) 之后的空格,正则表达式将寻找 " shop group for" 而不是 "shop group for"。如果您使用“^shop for|shop group for”),它将返回 2 个条目。
  • @phiver。这个cmets解决了问题,非常感谢!

标签: r filter dplyr


【解决方案1】:

由于您的数据中有明确的模式,您可以使用substr 来查找开头的单词'shop'。把它变成一个逻辑,并子集数据帧。

dd[substr(dd[,2], 1, 4)=='shop',]

  Code                Info
2    b       shop for test
4    d shop group for test

【讨论】:

    猜你喜欢
    • 2020-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-04
    • 2021-12-06
    • 1970-01-01
    相关资源
    最近更新 更多