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
  • 26,170
  • 12
  • 85
  • 119
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

13

Perhaps also:

(sample.int(101,size=100,replace=TRUE)-1)/100
Blue Magister
  • 13,044
  • 5
  • 38
  • 56
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
  • 40,856
  • 28
  • 97
  • 159
8

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,583
  • 7
  • 60
  • 79
Vineeth
  • 89
  • 2
  • 2
5

Or

x2 <- round( runif(100, -0.005, 1.0049, 2 )
vaettchen
  • 7,299
  • 22
  • 41
  • 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,931
  • 2
  • 19
  • 39
Codemaker2015
  • 12,190
  • 6
  • 97
  • 81