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
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
With base R
, you can do:
abbreviate("Department of Justice", 1, named = FALSE)
[1] "DoJ"
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 = "")
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 = "")
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"