New function add_padding() to avoid sprintf()

This commit is contained in:
Andreas Gammelgaard Damsbo 2023-09-05 14:10:45 -07:00
parent 163e970865
commit 8c65c5e13b
3 changed files with 81 additions and 0 deletions

38
R/add_padding.R Normal file
View File

@ -0,0 +1,38 @@
#' Add padding to string
#'
#' @param d vector of strings or numbers
#' @param length final string length
#' @param after if padding should be added after as opposed to default before
#' @param pad padding string of length 1
#'
#' @return vector or character strings of same length.
#' @export
#'
#' @examples
#' add_padding(sample(1:200,5))
add_padding <- function(d,length=NULL,after=FALSE,pad="0"){
if (!is.vector(d)) {
stop("Please supply vector")
}
if (nchar(pad)!=1) {
stop("Padding value should be just a single character or digit")
}
ns <- nchar(d)
if (is.null(length)){
l <- max(ns)
} else {
l <- length
}
ps <- unlist(lapply(l-ns,function(i){
paste(rep(pad,i),collapse="")}))
if (after) {
paste0(d,ps)
} else {
paste0(ps,d)
}
}

26
man/add_padding.Rd Normal file
View File

@ -0,0 +1,26 @@
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/add_padding.R
\name{add_padding}
\alias{add_padding}
\title{Add padding to string}
\usage{
add_padding(d, length = NULL, after = FALSE, pad = "0")
}
\arguments{
\item{d}{vector of strings or numbers}
\item{length}{final string length}
\item{after}{if padding should be added after as opposed to default before}
\item{pad}{padding string of length 1}
}
\value{
vector or character strings of same length.
}
\description{
Add padding to string
}
\examples{
add_padding(sample(1:200,5))
}

View File

@ -0,0 +1,17 @@
test_that("chunks_of_n returns correct", {
expect_length(add_padding(sample(1:200,5)),5)
expect_equal(nchar(add_padding(sample(1:200,5),5)), rep(5,5))
expect_equal(nchar(add_padding(
sample(1:200, 5), length = 5, after = TRUE
)), rep(5, 5))
## Errors
expect_error(add_padding(matrix(sample(1:200,5)),5))
expect_error(add_padding(matrix(sample(1:200,5)),5,pad = "123"))
})