Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get initials from string of words

Tags:

r

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?

like image 792
Eric Green Avatar asked Mar 20 '23 00:03

Eric Green


1 Answers

> 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" 
like image 124
Rich Scriven Avatar answered Mar 31 '23 12:03

Rich Scriven