过滤以字符串(str_detect)开头的条目

时间:2018-08-15 10:28:46

标签: r filter dplyr

过滤以字符串开头的条目

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)

所需的输出

Two entries. Desired output.

代码尝试

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

1 个答案:

答案 0 :(得分:0)

由于数据中存在清晰的模式,因此可以使用substr在开头查找单词'shop'。将其转换为逻辑数据并对数据框进行子集化。

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

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