0

Possible Duplicate:
R round to nearest .5 or .1
How do I round to 1, 1.5, 2 etc instead of 1, 2 or 1.1, 1.2, 1.3 in R?

if I want to round a number with some digits after comma

a <- 2.1357

I can use

round(a, 1)

to obtain 2.1 as result.

Now let I have an array of numbers like

b <- rnorm(n = 10, mean = .5, sd = .1)
> b
[1] 0.5554950 0.4527671 0.5217543 0.6137458 0.6023219 0.7045009 0.5140363 0.5312920
[9] 0.5841152 0.4492901

If I want to round those numbers in order to make them multiples of 0.1, it's enough to input

round(b, 1)

Now my question: what if I would like to round them in order to make the multiples of... 0.2? Or 0.3? Or 0.25... an so on?

Thanks,

Community
  • 1
  • 1
Lisa Ann
  • 3,345
  • 6
  • 31
  • 42
  • Duplicates: http://stackoverflow.com/questions/8664976/r-round-to-nearest-5-or-1, http://stackoverflow.com/questions/9502895/how-do-i-round-to-1-1-5-2-etc-instead-of-1-2-or-1-1-1-2-1-3-in-r – GSee Aug 17 '12 at 15:32

3 Answers3

6
a <- runif(20)  # Data
mult <- .125    # Multiple
mult*round(a/mult)

gets you

 [1] 0.250 0.750 0.125 0.625 0.000 0.500 0.125 0.500 0.125 0.875 1.000 0.750
[13] 0.500 0.500 0.125 0.500 0.250 0.250 0.250 0.875
Backlin
  • 14,612
  • 2
  • 49
  • 81
4

will this help

b <- rnorm(n = 10, mean = .5, sd = .1) 
b
library(plyr)
round_any(b, 0.1)
user1043144
  • 2,680
  • 5
  • 29
  • 45
2

The answer provided by @Backlin is the most straightforward way to go about doing this, but note that if you care about the distribution of the end result, you have to think carefully about how you are drawing your samples. For example, here is the result of 1 million draws from a random uniform using the straightforward method:

> a <- runif(1000000)
> mult <- 0.125
> samp <- mult * round(a/mult) 
> table(samp)

samp
     0  0.125   0.25  0.375    0.5  0.625   0.75  0.875      1 
 62889 125172 124564 125096 125443 124716 124899 124988  62233 

Notice that even though the original data were drawn from a uniform [0,1] distribution, 0 and 1 are underrepresented in the distribution of the rounded distribution. If you really wanted a random sample from a uniform between [0,1] in increments of 0.125, I would use sample and seq:

> rng <- seq(0, 1, 0.125)
> samp <- sample(rng, 1000000, replace=TRUE)
> table(samp)
samp
     0  0.125   0.25  0.375    0.5  0.625   0.75  0.875      1 
111206 111209 111222 110972 110617 111200 110827 111199 111548

This is how I would suggest you draw from a uniform distribution. If you want to put different weights on the possible results, you could use the prob argument to sample. If you are wanting to draw from a different distribution that doesn't have a clearly defined upper and lower bound, such as the normal distribution, you may or may not have similar problems. You will need to think carefully and run many tests to make sure you are getting the distribution you want.

Jason Morgan
  • 2,260
  • 21
  • 24