R中的调整不起作用(Regmatches in R not working)

编程入门 行业动态 更新时间:2024-10-12 03:18:19
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"

更多推荐

本文发布于:2023-07-19 04:49:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1173726.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:不起作用   Regmatches   working

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!