stats_noob
stats_noob

Reputation: 5907

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

Upvotes: 3

Views: 4893

Answers (4)

Andreas Ravache
Andreas Ravache

Reputation: 68

Two other ways to generate two random integers using runif :

a <-  round(runif(1000000, min=-0.5000001, max=1.4999999), 0)
table(a)

b <-  floor(runif(1000000, min=0.00000001, max=1.9999999))
table(b)

Upvotes: 1

eleni1982
eleni1982

Reputation: 11

round(stats::runif(1000), digits = 0)

The default values of min and max are 0 and 1 in runif. round() rounds to the closest integer.

Upvotes: 1

GKi
GKi

Reputation: 39657

To generate random integer numbers of 0 or 1 you can use rbinom or sample.

x <- rbinom(1000, 1, 0.5)
str(x)
# int [1:1000] 0 1 1 0 1 1 0 1 0 1 ...
x <- sample(0:1, 1000, TRUE)
str(x)
# int [1:1000] 1 0 0 0 1 1 1 0 0 0 ...

In case you have only 0 and 1 maybe it would be better to use a logical vector allowing only TRUE and FALSE.

x <- sample(c(TRUE, FALSE), 1000, TRUE)
str(x)
# logi [1:1000] TRUE TRUE TRUE FALSE TRUE FALSE ...

Upvotes: 5

Ronak Shah
Ronak Shah

Reputation: 388982

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.

Upvotes: 2

Related Questions