[英]R, regexpr,gregexpr, keep track of matches
假設我有此data.frame,並希望將A列與以下模式匹配。 這可以使用regexpr或gregexpr來完成。 但是我想跟蹤匹配的行以及匹配本身。
df <- data.frame(A=c("where is the pencil? ","the white cat in the kitchen","green hat is over the blue ocean"))
> df
## A
## 1 where is the pencil?
## 2 the white cat in the kitchen
## 3 green hat is over the blue ocean
pattern <- ("(blue|white|green) \\w*")
regmatches(df[,1],regexpr(pattern,df[,1],perl=TRUE))
> regmatches(df[,1],regexpr(pattern,df[,1],perl=TRUE))
## [1] "white cat" "green hat"
所需的輸出:
## A match
## 1 where is the pencil? <NA>
## 2 the white cat in the kitchen white cat
## 3 green hat is over the blue ocean green hat
將pattern
更改為:
pattern <- paste0(pattern, "|$")
然后將空字符串替換為NA
。 不需要perl=TRUE
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.