Truncate character strings after first N characters

There is already a packaged function for this operation. Try str_trunc() from the stringr package, setting the width to 13 (10 chars + 3 dots).

stringr::str_trunc(a, 13)
# [1] "AMS"           "CCD"           "TCGGCKGTPG..." "NOK"           
# [5] "THIS IS A ..." "JSQU909LPPLU" 

kind of faster ...

ifelse(nchar(a) > 13, paste0(strtrim(a, 10), '...'), a)

I think the simplest way to do that is by using substr, that does not require any packages

      a <- c("AMS", "CCD", "TCGGCKGTPGPHOLKP", "NOK", "THIS IS A LONG STRING","JSQU909LPPLU")
  
 #It will keep only chars from 1-10 for each element
      substr(a,1,10)

[1] "AMS"        "CCD"        "TCGGCKGTPG" "NOK"        "THIS IS A "
[6] "JSQU909LPP"

Solution using ifelse and substring:

Edit (after @G5W comment):

a <- c("AMS", "CCD", "TCGGCKGTPGPHOLKP", "NOK", "THIS IS A LONG STRING", "JSQU909LPPLU")
ifelse(nchar(a) > 13, paste0(substring(a, 1, 10), "..."), a)

Tags:

R