16

I need to do a pretty simple task,but since im not versed in R I don't know exactly how to. I have to create a vector of 100 numbers with random values from 0 to 1 with 2 DECIMAL numbers. I've tried this:

 x2 <- runif(100, 0.0, 1.0)

and it works great, but the numbers have 8 decimal numbers and I need them with only 2.

Paul
  • 24,493
  • 12
  • 81
  • 118
Pablo Romero
  • 161
  • 1
  • 1
  • 3
  • 6
    Do you really need numbers with 2dp, or only need them _displayed_ with 2 dp? If it's the latter, `sprintf("%.2f", x2)` – Hong Ooi Jul 21 '13 at 13:21

6 Answers6

12

Perhaps also:

(sample.int(101,size=100,replace=TRUE)-1)/100
Blue Magister
  • 12,516
  • 5
  • 36
  • 55
9

So you want to sample numbers randomly from the set { 0, 1/100, 2/100, ..., 1 }? Then write exactly that in code:

hundredths <- seq(from=0, to=1, by=.01)
sample(hundredths, size=100, replace=TRUE)
Ryan C. Thompson
  • 38,976
  • 28
  • 92
  • 152
7

Hope this helps

x1 = round(runif(100,0,1), 2)
  • 100: Number of random numbers
  • 0: Min value
  • 1: max value
  • 2: rounded to two decimal palaces
gung - Reinstate Monica
  • 11,223
  • 7
  • 58
  • 75
Vineeth
  • 79
  • 1
  • 2
5

Or

x2 <- round( runif(100, -0.005, 1.0049, 2 )
vaettchen
  • 7,031
  • 20
  • 39
  • 4
    You cannot see Paul's deleted answer... This is not correct because the end points (`0.00` and `1.00`) will have half the probability of all other points. – flodel Jul 21 '13 at 15:31
  • @flodel -you are right, thanks. I was just modifiying the OP's approach, but probably he himself didn't think of it. Edited so that the probabilities should now be correct. – vaettchen Jul 22 '13 at 00:41
3

Simple fix: x2 <- round(runif(100, 0.0, 1.0), digits=2)

Will round to two DP.

0

You can use round over runif to generate random numbers.

Vector = round(runif(number of random numbers, min value, max value), decimal places)

Eg: Vector = round(runif(10,0,1),3) //it generate 10 random numbers with 3 decimal places

Davide
  • 1,566
  • 1
  • 16
  • 37
Codemaker
  • 7,952
  • 3
  • 61
  • 53