Position of Approximate Substring Matches in R

谁说胖子不能爱 提交于 2019-12-07 18:56:46

问题


I'm using R for string processing. I have a data frame with a column of strings, say:

 df <- data.frame(textcol=c("In this substring would like to find the position of this substring",
 "I would also like to find the position of thes substring",
 "No match here","No mention of this substrangy thing"))

 matchPattern <- "this substring"

I am searching for a function that (depending on a distance parameter of some sort, say Jarro-Winkler) would take my matchPattern, compare it to every row of the data frame text column, and return the exact position of the match within the matched string, i.e. 36 (unless I miscounted) for the first element, and (perhaps) 43 for the second, NA for the third and 14 (?) for the the fourth.


回答1:


You could use aregexec

## Get positions (-1 instead of NA)
positions <- aregexec(matchPattern, df$textcol, max.distance = 0.1)
unlist(positions)
# [1] 38 43 -1 15

## Extract matches
regmatches(df$textcol, positions)
# [[1]]
# [1] "this substring"
# 
# [[2]]
# [1] "thes substring"
# 
# [[3]]
# character(0)
# 
# [[4]]
# [1] "this substrang"

Edit

## A possibilty for replacing matches, or maybe `regmatches<-`
res <- regmatches(df$textcol, positions)
res[lengths(res)==0] <- "XXXX"  # deal with 0 length matches somehow
df$out <- Vectorize(gsub)(unlist(res), "Censored", df$textcol)
df$out
# [1] "I would like to find the position of Censored"     
# [2] "I would also like to find the position of Censored"
# [3] "No match here"                                     
# [4] "No mention of Censoredy thing"                     


来源:https://stackoverflow.com/questions/31843171/position-of-approximate-substring-matches-in-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!