Skip to content

Instantly share code, notes, and snippets.

@artemklevtsov
Last active May 20, 2016 05:48
Show Gist options
  • Save artemklevtsov/da32e34c3d98666a762a to your computer and use it in GitHub Desktop.
Save artemklevtsov/da32e34c3d98666a762a to your computer and use it in GitHub Desktop.
Based on the stringi::stri_pad and tools::showNonASCII
str_pad <- function(str, width = floor(0.9 * getOption("width")), side = c("left", "both", "right")) {
side <- match.arg(side)
asc <- iconv(str, "latin1", "ASCII")
if (any(is.na(asc) | asc != str))
width <- width + nchar(str, "bytes") - nchar(str, "width")
switch(side,
left = sprintf("%*s", width, str),
right = sprintf("%-*s", width, str),
both = sprintf("%-*s", width, sprintf("%*s", floor(width / 2), str)))
}
@artemklevtsov
Copy link
Author

Example:

paste(str_pad("One", 20), 1)
#> [1] "One                  1"
paste(str_pad("Один", 20), 1)
#> [1] "Один                 1"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment