R中的调整不起作用(Regmatches in R not working)
我正在尝试向R中的数据集添加一列。该列应该是名称列的首字母缩写。 我正在尝试使用lapply并传递一个函数来获取首字母缩写 - 但是,我无法使这个正则表达式正常工作。
pattern <- "(\b[a-zA-Z])" str<-"MICHAEL, JENSON F" m <- regexpr(pattern,str,perl=TRUE) regmatches(str,m)返回字符(0)
我如何让R返回一个字符串匹配的列表? 我想重新匹配MJ和F.
I am trying to add a column to a data set in R. The column should be the initials from a name column. I am trying to use lapply and passing in a function to get the initials - however, I can't get this regexp to work.
pattern <- "(\b[a-zA-Z])" str<-"MICHAEL, JENSON F" m <- regexpr(pattern,str,perl=TRUE) regmatches(str,m)Returns character(0)
How can I have R return a list of matches of a string? I want regmatches to return M J and F.
最满意答案
有两个问题: \b必须转义,您应该使用gregexpr而不是regexpr因为后者只返回第一个匹配项。
pattern <- "(\\b[a-zA-Z])" str<-"MICHAEL, JENSON F" m <- gregexpr(pattern,str,perl=TRUE) regmatches(str,m)[[1]] # [1] "M" "J" "F"There are two problems: \b must be escaped and you should use gregexpr instead of regexpr because the latter returns only the first match.
pattern <- "(\\b[a-zA-Z])" str<-"MICHAEL, JENSON F" m <- gregexpr(pattern,str,perl=TRUE) regmatches(str,m)[[1]] # [1] "M" "J" "F"更多推荐
发布评论