简体   繁体   中英

Function turning a string into acronym in R

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)?

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 = ''))
}

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" ) 
    }

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")

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

abbreviate(x, minlength = 1)

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM