当前位置: 动力学知识库 > 问答 > 编程问答 >

r - regarding finding a string in a given vector

问题描述:

Given a string, like xyz, and a string vector, like

abc

xyz

cde

fgh

xyz

Is there a function that can output the position of xyz in this vector, here it should be (2,5); as well as the number of occurrence, here it should be 2.

网友答案:
library(stringr)
yourlist = c("abc", "xyz", "cde", "fgh", "xyz")
which(str_detect(yourlist, "xyz"))

This will return 2 and 5.

网友答案:

One other approach, with base R:

regmatches(yourlist, gregexpr(pattern = "xyz", text = yourlist,ignore.case = TRUE, perl = TRUE))
[[1]]
character(0)

[[2]]
[1] "xyz"

[[3]]
character(0)

[[4]]
character(0)

[[5]]
[1] "xyz"

The output is longer, but it also confirm what was found ("xyz") and what locations

分享给朋友:
您可能感兴趣的文章:
随机阅读: