Reputation: 7928
I would like to change a range of names to simply their initials,
Say I have two names c("Ben Franklin", "Millard Fillmore")
and I would like to subset them to c("BF", "MF")
, I have read the help fil eto ?gsub
but I cannot figure it out. Can anyone here help me?
Upvotes: 2
Views: 610
Reputation: 269895
This removes everything that is not an upper case letter:
> s <- c("Ben Franklin", "Millard Fillmore")
> gsub("[^A-Z]", "", s)
[1] "BF" "MF"
Here is a more complex regular expression if you have strings such "Allan McCormick" as per comments:
s <- c("Ben Franklin", "Millard Fillmore", "Allen McCormick")
gsub("(.)\\S* *", "\\1", s)
[1] "BF" "MF" "AM"
Upvotes: 2
Reputation: 121598
just with gsub
gsub(pattern='(.)(.*)[[:space:]](.)(.*)','\\1\\3',c("Ben Franklin", "Millard Fillmore"))
"BF" "MF"
Upvotes: 1
Reputation: 49820
Split the strings on " "
, then apply the substr
function to each component and collapse the results with paste
> x <- c("Ben Franklin", "Millard Fillmore")
> sapply(strsplit(x, " "), function(x) paste(substr(x, 1, 1), collapse=""))
[1] "BF" "MF"
Upvotes: 2