3

I want to round numbers to the closest half or whole number. So I want to round 4.2 to 4, 4.3 to 4.5 and 4.8 to 5. I tried a few things with the round option:

> round(4.34,1)
[1] 4.3
> round(4.34)
[1] 4
> round(4.34,0.5)
[1] 4.3
> round(4.34,2)
[1] 4.34

So I only know how to increase the amount of significant numbers, but not how to do different kinds of rounding. Can that be done with the round function, or is there a different function to do that in R?

Niek de Klein
  • 8,524
  • 20
  • 72
  • 143
  • 3
    I don't know R, but can you double the number, then round it, then divide by 2? Such as 4.34 * 2 is 8.68, round up to 9, then divide by 2. – Mike Christensen Feb 29 '12 at 16:32

3 Answers3

14

Use the function round_any in package plyr:

library(plyr)

x <- 4.34

round_any(x, 3)
[1] 3

round_any(x, 1)
[1] 4

round_any(x, 0.5)
[1] 4.5

round_any(x, 0.2)
[1] 4.4
Andrie
  • 176,377
  • 47
  • 447
  • 496
11

This works without any extra package:

x <- c(4.2, 4.3, 4.8)
round(x*2)/2
#[1] 4.0 4.5 5.0
Tommy
  • 39,997
  • 12
  • 90
  • 85
5

I don't know R, but I believe this would work, syntax aside:

y = x / 5
z = round(y, 1)
r = z * 5
Andy
  • 8,870
  • 1
  • 31
  • 39