Search code examples
rrandomintegerrange

R: Generate Random Numbers with "floor" and "runif"


I am using the R programming language. I am trying to generate random integers between 1 and 0. Using the following link (http://www.cookbook-r.com/Numbers/Generating_random_numbers/), I tried this code to generate 1000 random integers between 0 and 1:

x = floor(runif(1000, min=0, max=1))
y = floor(runif(1000, min=0, max=1))
group <- sample( LETTERS[1:2], 1000, replace=TRUE, prob=c(0.8,0.2) )

d = data.frame(x,y,group)
d$group = as.factor(d$group)

However, both "x" and "y" seem to only have a value of 0.

Does anyone know what I am doing wrong? Thanks


Solution

  • From ?floor

    floor takes a single numeric argument x and returns a numeric vector containing the largest integers not greater than the corresponding elements of x.

    Let's look at an example to understand this -

    floor(c(5.3, 9.9, 6.5, 1.2))
    [1] 5 9 6 1
    

    floor always rounds down to nearest integer. In your example, with runif you are generating numbers between 0 and 1 and since you are using floor all the numbers are rounded down to 0 hence you only get 0 as output.