File: clipString.R

package info (click to toggle)
r-cran-bbmisc 1.13.1-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 1,256 kB
  • sloc: ansic: 176; sh: 9; makefile: 5
file content (25 lines) | stat: -rw-r--r-- 958 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#' @title Shortens strings to a given length
#'
#' @description
#' Clips strings to a maximum length, appending a tail if shortened.
#'
#' @param x [\code{character}]\cr
#'   Vector of strings.
#' @param len [\code{integer(1)}]\cr
#'   Absolute length the string should be clipped to, including \code{tail}.
#'   Note that you cannot clip to a shorter length than \code{tail}.
#' @param tail [\code{character(1)}]\cr
#'   If the string has to be shortened at least 1 character, the final characters will be \code{tail}.
#'   Default is \dQuote{...}.
#' @return [\code{character(1)}].
#' @export
#' @examples
#' print(clipString("abcdef", 10))
#' print(clipString("abcdef", 5))
clipString = function(x, len, tail = "...") {
  assertCharacter(x, any.missing = TRUE)
  len = asInteger(len, len = 1L, lower = nchar(tail))
  assertString(tail)
  ind = (!is.na(x) & nchar(x) > len)
  replace(x, ind, paste(substr(x[ind], 1L, len - nchar(tail)), tail, sep = ""))
}