Function turning a string into acronym in R

237 views Asked by At

I have a string "California Art Craft Painting Society" and I want to write a function x in R that can turn any string into an acronym "CACPS". I used the following code:

acronym <- function(x){
  abbreviate(x)
}  

Is there a way to write the function using stringr such as strsplit the string first, then use strsub to pull the first letter of each word (not use abbreviate)?

4

There are 4 answers

0
Ronak Shah On

If you want to use string split approach, try this

acronym <- function(x) {
  sapply(strsplit(x, ' '), function(y) paste0(substr(y, 1, 1), collapse = ''))
}

acronym(c("California Art Craft Painting Society", 'A Big Word'))
#[1] "CACPS" "ABW" 

Or using stringr :

library(purrr)
library(stringr)

acronym <- function(x) {
  map_chr(str_split(x, ' '), function(y) str_c(str_sub(y, 1, 1), collapse = ''))
}
0
Brendan On

This might be of use. It uses str_remove_all on characters which are not preceded by a word break, and also removes any spaces.

library(stringr)

create_acronym <- function(x){
      str_remove_all(x , "(?<!\\b)\\w|\\s" ) 
    }
0
ThomasIsCoding On

A gsub option

> gsub("\\b([A-Z])(\\w+)?\\s?", "\\1", v)
[1] "CACPS" "ABW"

Data

v <- c("California Art Craft Painting Society", "A Big Word")
1
symbolrush On

IMHO the most simple (and also most concise) option is as simple as:

abbreviate(x, minlength = 1)