RoyalTS
RoyalTS

Reputation: 10203

R: Truncate string without splitting words

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.

Upvotes: 6

Views: 841

Answers (2)

Josh O&#39;Brien
Josh O&#39;Brien

Reputation: 162401

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 ..."

Upvotes: 4

Paul Hiemstra
Paul Hiemstra

Reputation: 60964

I would recommend you take a look at the abbreviate function. It abbreviates strings, and allows some control. See:

http://stat.ethz.ch/R-manual/R-devel/library/base/html/abbreviate.html

For the man page.

Upvotes: 0

Related Questions