Filter a vector of strings based on string matching

后端 未结 4 1154
[愿得一人]
[愿得一人] 2020-12-30 19:43

I have the following vector:

X <- c(\"mama.log\", \"papa.log\", \"mimo.png\", \"mentor.log\")

How do I retrieve another vector that only

4条回答
  •  孤城傲影
    2020-12-30 20:25

    The documentation on the stringr package says:

    str_subset() is a wrapper around x[str_detect(x, pattern)], and is equivalent to grep(pattern, x, value = TRUE). str_which() is a wrapper around which(str_detect(x, pattern)), and is equivalent to grep(pattern, x).

    So, in your case, the more elegant way to accomplish your task using tidyverse instead of base R is as following.

    library(tidyverse)
    
    c("mama.log", "papa.log", "mimo.png", "mentor.log") %>% 
       str_subset(pattern = "^m.*\\.log")
    

    which produces the output:

    [1] "mama.log"   "mentor.log"
    

提交回复
热议问题