Skip to content

Instantly share code, notes, and snippets.

@dsparks
Created February 9, 2011 18:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dsparks/818990 to your computer and use it in GitHub Desktop.
Save dsparks/818990 to your computer and use it in GitHub Desktop.
create string variable from numeric variable with padding 0s
Pad0 <- function(x, mx=NULL, fill=0) {
## pad numeric vars to strings of specified size
lx <- nchar(as.character(x))
mx.calc <- max(lx, na.rm=TRUE)
if (!is.null(mx)) {
if (mx<mx.calc) {
stop("number of maxchar is too small")
}
} else {
mx <- mx.calc
}
px <- mx-lx
paste(sapply(px,function(x) paste(rep(fill,x),collapse="")),x,sep="")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment