10

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

NelsonGon
  • 13,015
  • 7
  • 27
  • 57
IVIM
  • 2,167
  • 1
  • 15
  • 41
  • I use `str_remove_all(full_names, "(?<!^|[:space:]).")`. The regex matches all characters that are not preceded by the start of the string or a space, so they're removed, and only the first letter of each word, including the first word, remains. – DHW Jan 09 '20 at 17:15

4 Answers4

28

With base R, you can do:

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

[1] "DoJ"
tmfmnk
  • 38,881
  • 4
  • 47
  • 67
5

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 = "")
Prometheus
  • 673
  • 3
  • 25
  • 2
    To get the desired result, I think you'd need to add a call to `paste` like this `paste(str_sub(as.list(new_list[[1]]),1,1), collapse = "")`, which gives `"DoJ"`. Otherwise, you get `"D" "o" "J"`. – Dan May 08 '19 at 16:45
  • Yes. That would give the final answer OP requested. Thanks a lot for pointing this out. @Lyngbakr . I will add this line to the above code. – Prometheus May 08 '19 at 16:47
2

An alternative but overly "complicated" base solution:

paste(unlist(lapply(strsplit(strDept," "),function(x) substring(x,1,1))),collapse = "")
#[1] "DoJ"

You can avoid lapply as suggested by @Lyngbakr:

 paste(substring(unlist(strsplit(strDept," ")), 1, 1), 
       collapse = "")
[1] "DoJ"

If you want to stick with stringr:

paste(substring(stringr::str_split(strDept, pattern = " ", simplify = TRUE), 1, 1), collapse = "")
NelsonGon
  • 13,015
  • 7
  • 27
  • 57
2

I really like @tmfmnk solution, however if you want to stick to stringr you could use this:

library(purrr)
library(stringr)
x = "Department of Justice"
x %>% 
  str_split(pattern = " ") %>%
  map(str_trunc, 1, ellipsis = "") %>%
  map(str_c, collapse="") %>%
  flatten_chr()

[1] "DoJ"
MrNetherlands
  • 920
  • 7
  • 14