Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R: Truncate string without splitting words

Tags:

string

r

I have bunch of strings, some of which are fairly long, like so:

movie.titles <- c("Il divo: La spettacolare vita di Giulio Andreotti","Defiance","Coco Before Chanel","Happy-Go-Lucky","Up","The Imaginarium of Doctor Parnassus")

I would now like to truncate these strings to a maximum of, say, 30 characters, but in such a way that no words are split up in the process and ideally such that if the string is truncated ellipses are added to the end of the string.

like image 488
RoyalTS Avatar asked Jun 19 '12 12:06

RoyalTS


1 Answers

Here's an R-based solution:

trimTitles <- function(titles) {
    len <- nchar(titles)
    cuts <- sapply(gregexpr(" ", titles), function(X) {
            max(X[X<27])})
    titles[len>=27] <- paste0(substr(titles[len>=27], 0, cuts[len>=27]), "...")
    titles
}
trimTitles(movie.titles)
# [1] "Il divo: La spettacolare ..."  "Defiance"                     
# [3] "Coco Before Chanel"            "Happy-Go-Lucky"               
# [5] "Up"                            "The Imaginarium of Doctor ..."
like image 122
Josh O'Brien Avatar answered Sep 28 '22 10:09

Josh O'Brien