2

I am trying to round number by rounding units.

For example,

value <- c(8.21,1.76, 6.42,1.94,10.38)

if rounding unit is 0.2, the results would be

(8.2, 1.8, 6.4, 2.0, 10.4).

How can I do it in R? Thanks for your inputs.

Gavin Simpson
  • 170,508
  • 25
  • 396
  • 453
lucyh
  • 179
  • 2
  • 5
  • 14

1 Answers1

6
round.to <- function(x, b) {
  round(x/b)*b
}

round.to(value, .2)
## [1]  8.2  1.8  6.4  2.0 10.4

This technique also works for b>1:

round.to(value, 2)
## [1]  8  2  6  2 10
Matthew Lundberg
  • 42,009
  • 6
  • 90
  • 112