StrTrunc: Truncate Strings and Add Ellipses If a String is Truncated.

StrTruncR Documentation

Truncate Strings and Add Ellipses If a String is Truncated.

Description

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.

Usage

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

Arguments

x

a vector of strings.

maxlen

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

ellipsis

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

wbound

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

Value

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

Author(s)

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

See Also

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

Examples

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))

AndriSignorell/DescTools documentation built on Dec. 1, 2024, 5:13 a.m.