Search code examples
rstringdoublesubstr

How to code a substr version that holds leading zeros in numeric values (in R)?


While preparing a function that converts normalized double precision numbers to decimal numbers, I needed something like following:

substr(01001011, 2, 5) # what is in fact:"0010" (because leading 0 is ignored)
substr(01001011, 2, 5) # what I want:"1001"
substr("01001011", 2, 5) # "1001"; gives what I want BUT the following:

In substr("01001011", 2, 5), it is impossible (for me) to turn it to a function since input=01001011 and double quote concatenations very very problematic. Each time the user must manually enter the value of argument not in in function's call but also in the body of the function where substr(...) part is located.

The problem caused by the fact that 01001011 is hold as numeric and hence all leading 0s are ignored.

01001011 # [1] 1001011
class(01001011) # "numeric"

substrCorrectly <- function(x) {
substr("x", 2, 5) }

For example, for number "01001011";

substrCorrectly <- function(x) {
substr("01001011", 2, 5) }
substrCorrectly(01001011) # "1001"

This function is definitely very ugly, and against the notion of function: Each time user must change the body of function before applying it!

Any idea?

More examples:

substr(000101001011, 1, 4) # "1010"; but what I want is 0001 here. 
substr(10001, 1, 2) # "10" and what I want (10) coincides since 1 is leading. 

Solution

  • You can use formatC that will allows to keep first 0s

    substrCorrectly <- function(x) { 
      x <- formatC(x, flag="0", width=8, format="d") 
      substr(x, 2, 5) 
    }
    substrCorrectly(01001011) # "1001"