How to split a number into digits in R

后端 未结 7 610
花落未央
花落未央 2021-02-01 17:38

I have a data frame with a numerical ID variable which identify the Primary, Secondary and Ultimate Sampling Units from a multistage sampling scheme. I want to split the origina

7条回答
  •  [愿得一人]
    2021-02-01 18:27

    Since they are numbers, you will have to do some math to extract the digits you want. A number represented in radix-10 can be written as:

    d0*10^0 + d1*10^1 + d2*10^2 ... etc. where d0..dn are the digits of the number.
    

    Thus, to extract the most significant digit from a 6-digit number which is mathematically represented as:

    number = d5*10^5 + d4*10^4 + d3*10^3 + d2*10^2 + d1*10^1 + d0*10^0
    

    As you can see, dividing this number by 10^5 will get you:

    number / 10^5 = d5*10^0 + d4*10^(-1) + d3*10^(-2) + d2*10^(-3) + d1*10^(-4) + d0*10^(-5)
    

    Voila! Now you have extracted the most significant digit if you interpret the result as an integer, because all the other digits now have a weight less than 0 and thus are smaller than 1. You can do similar things for extracting the other digits. For digits in least significant position you can do modulo operation instead of division.

    Examples:

    501901 / 10^5 = 5 // first digit
    501901 % 10^5 = 1 // last digit
    (501901 / 10^4) % 10^1 = 0 // second digit
    (501901 / 10^2) % 10^2 = 19 // third and fourth digit
    

提交回复
热议问题