R: Truncate a string without splitting words

I have a set of strings, some of which are quite long, for example:

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

Now I would like to trim these lines with a maximum of, say, 30 characters, but in such a way that no words are split in the process and ideally such that if a line of truncated ellipses is added to the end of the line.

+6
source share
2 answers

Here's the R 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 ..." 
+4
source

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

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

For the man page.

0
source

Source: https://habr.com/ru/post/918466/


All Articles