Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to abbreviate a string in R [duplicate]

Tags:

r

stringr

I need to abbreviate department names by their first character, so that strDept="Department of Justice" becomes strDeptAbbr = "DoJ".

How can I abbreviate a string using stringr?
Thank you

like image 279
IVIM Avatar asked May 08 '19 16:05

IVIM


2 Answers

With base R, you can do:

abbreviate("Department of Justice", 1, named = FALSE)

[1] "DoJ"
like image 183
tmfmnk Avatar answered Sep 20 '22 08:09

tmfmnk


You can use:

library(stringr)
x="Department of Justice"
new_list=strsplit(x, " ")
str_sub(as.list(new_list[[1]]),1,1)

The previous answer by @tmfmnk is much better in my opinion.

Edit:

As @Lyngbakr pointed out, the following code will yield the final result requested:

paste(str_sub(as.list(new_list[[1]]),1,1), collapse = "")
like image 20
Prometheus Avatar answered Sep 21 '22 08:09

Prometheus