Search code examples
rrounding

Finding the correct rounding value to output non-0 values


I have a vector of decimal numbers ranging from -10 to 10 with different decimal depth.

I would like to output a rounded version of this vector so that all numbers are rounded at the level of the decimal number which last shows a non-0 decimal (e.g. 0.0040 shows a non-0 decimal after 0.1000, the rounding should be 3). My goal is to always output non-0 values after rounding my vector.

In the following example, the decimal number showing a first non-0 value is 0.000100, thus all numbers should be rounded to 4. The value 1.000002 should not be rounded to 6 because it is already different to 0.

### Initiating vector of values, only 0s and 1s should be displayed because the deepest decimal level is 4. 2s should not be displayed
tmpVector <- c(0.111120, -11.011102, 0.001100, 0.000100, 1.000002, -0.101022)

### Correct rounding
round(tmpVector, 4)

[1] 0.1111 -11.0111   0.0011   0.0001   1.0000  -0.1010

I would like to find an automatic method where I can replace round(tmpVector, 4) with round(tmpVector, deepestLevel).

Couldn't find other versions of round() function taking care of this problematic.


Solution

  • OK, so we can extract the lowest exponent like so:

    tmpVector[tmpVector!=0] |> # remove zeros
      abs() |> # some values are negative - we don't care
      log10() |> # log gives us the exponent
       min() |>  # find the smallest
      floor() |> # make an integer
      abs() # stop it being negative
    
    # gives:
    4
    

    then incorporate that into round():

    round(tmpVector, tmpVector[tmpVector!=0] |> abs() |> log10() |> min() |> floor() |> abs())
    [1]   0.1111 -11.0111   0.0011   0.0001   1.0000  -0.1010
    

    or avoiding pipe notation:

    round(tmpVector, abs(floor(min(log10(abs(tmpVector[tmpVector!=0]))))))