The main purpose was to correct ID numbers in studies that are entered as integers with leading 0's as in 000001 or 034554. R's default coercion of integers will throw away the preceding 0's, and reduce that to 1 or 34554. The user might want to re-insert the 0's, thereby creating a character vector with values "000001" and "045665".
padW0(x, n = 0)
vector to be converted to a character variable by inserting 0's at the front. Should be integer or character, floating point numbers will be rounded down. All other variable types will return errors.
Optional parameter. The desired final length of
character vector. This parameter is a guideline to determine
how many 0's must be inserted. This will be ignored if
If x is an integer or a character vector, the result is the more-or-less expected outcome (see examples). If x is numeric, but not an integer, then x will be rounded to the lowest integer.
The previous versions of this function failed when there were missing values (NA) in the vector x. This version returns NA for those values.
One of the surprises in this development was that sprintf() in R
does not have a known consequence when applied to a character
variable. It is platform-dependent (unredictable). On Ubuntu Linux
16.04, for example
sprintf("%05s", 2) gives back
" 2", rather than (what I expected)
problem is mentioned in the documentation for
examples show this does work now, but please test your results.
A character vector
Paul Johnson <email@example.com>
1 2 3 4 5 6 7 8 9 10 11
x1 <- c(0001, 0022, 3432, NA) padW0(x1) padW0(x1, n = 10) x2 <- c("1", "22", "3432", NA) padW0(x2) ## There's been a problem with strings, but this works now. ## It even preserves non-leading spaces. Hope that's what you want. x3 <- c("1", "22 4", "34323 42", NA) padW0(x3) x4 <- c(1.1, 334.52, NA) padW0(x4)
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.