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 MJ and 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"
只是想出了Stringr库。
str_match_all(str, "(\\b[a-zA-Z])[a-zA-Z]* ?")
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.