14
votes

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.

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

6 Answers

11
votes

Perhaps also:

(sample.int(101,size=100,replace=TRUE)-1)/100
8
votes

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)
5
votes

Or

x2 <- round( runif(100, -0.005, 1.0049, 2 )
5
votes

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
3
votes

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

Will round to two DP.

0
votes

You can use round and runif methods 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