【发布时间】:2015-03-05 14:29:36
【问题描述】:
假设我有这个 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
【问题讨论】: