Eric Green
Eric Green

Reputation: 7735

get initials from string of words

What I have:

names <- c("First Last", "First M Last", "First M. Last", "first Last", "first lAst")

What I want:

"FL" "FML" "FML" "FL" "FL"

What I tried:

paste(substr(strsplit(names, " ")[[1]], 1, 1), collapse="")

What this gives:

FL

How can I get this for all elements?

Upvotes: 4

Views: 2812

Answers (3)

Rich Scriven
Rich Scriven

Reputation: 99361

> names <- c("First Last", "First M Last", "First M. Last", 
             "first Last", "first lAst")

It looks like you want the result to be all upper case? If that's the case, we can use toupper inside sapply with similar code to what you've tried.

> s <- strsplit(names, " ")
> sapply(s, function(x){
      toupper(paste(substring(x, 1, 1), collapse = ""))
  })
# [1] "FL"  "FML" "FML" "FL"  "FL" 

Upvotes: 7

Matthew Plourde
Matthew Plourde

Reputation: 44614

Here's another option using regular expressions:

# find letters preceded by a space (\\s) or the beginning of the string (^)
regex <- '(?<=^|\\s)[[:alpha:]]' 
initials <- regmatches(names, gregexpr(regex, names, perl=TRUE))
toupper(sapply(initials, paste0, collapse=''))
# [1] "FL"  "FML" "FML" "FL"  "FL" 

Upvotes: 0

IRTFM
IRTFM

Reputation: 263451

If you run your own logic over each element you get the desired results:

sapply( names, function(x)
                  paste(substr(strsplit(x, " ")[[1]], 1, 1), collapse="") )

If you do not like the names You can unname the result:

> unname(sapply( names, function(x)
+ paste(substr(strsplit(x, " ")[[1]], 1, 1), collapse="") ))
[1] "FL"  "FML" "FML" "fL"  "fl" 

Or use the USE.NAMES parameter:

> sapply( names, function(x)
+ paste(substr(strsplit(x, " ")[[1]], 1, 1), collapse="") , USE.NAMES=FALSE)
[1] "FL"  "FML" "FML" "fL"  "fl" 

Upvotes: 1

Related Questions