StrTrunc {DescTools}R Documentation

Truncate Strings and Add Ellipses If a String is Truncated.


Truncates one or more strings to a specified length, adding an ellipsis (...) to those strings that have been truncated. The truncation can also be performed using word boundaries. Use StrAlign() to justify the strings if needed.


StrTrunc(x, maxlen = 20, ellipsis = "...", wbound = FALSE)



a vector of strings.


the maximum length of the returned strings (NOT counting the appended ellipsis). maxlen is recycled.


the string to be appended, if the string is longer than the given maximal length. The default is "...".


logical. Determines if the maximal length should be reduced to the next smaller word boundary and so words are not chopped. Default is FALSE.


The string(s) passed as ‘⁠x⁠’ now with a maximum length of ‘⁠maxlen⁠’ + 3 (for the ellipsis).


Andri Signorell,
once following an idea of Jim Lemon in truncString()

See Also

String functions: nchar, match, grep, regexpr, substr, sub, gsub, StrTrim, StrDist


x <- c("this is short", "and this is a longer text", 
       "whereas this is a much longer story, which could not be told shorter")

# simple truncation on 10 characters
StrTrunc(x, maxlen=10)

# NAs remain NA
StrTrunc(c(x, NA_character_), maxlen=15, wbound=TRUE)

# using word boundaries
for(i in -5:20)
  print(StrTrunc(x, maxlen=i, wbound=TRUE))

# compare
for(i in -5:20)
  print(StrTrunc(x, maxlen=i, wbound=FALSE))

[Package DescTools version 0.99.51 Index]