R Generate Random Numbers with floor and runif

0 votes
The R programming language is what I'm utilising. I'm attempting to produce random integers in the range between 1 and 0. I tried the following code to produce 1000 random integers between 0 and 1 .

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

the data frame d (x,y,group)
as.factor(d$group) = d$group
But it appears that "x" and "y" only have a value of 0.

Can somebody tell me what I'm doing incorrectly? Thanks
Jul 22, 2022 in Data Science by avinash
• 1,840 points
• 3,230 views

1 answer to this question.

0 votes

It looks like there's a small issue with the code you provided. The problem is that you're trying to generate random integers between 0 and 1, but `runif` generates random numbers from a continuous uniform distribution between the specified `min` and `max` values. To generate random integers, you need to round or floor the results.

Here's the corrected code to generate 1000 random integers between 0 and 1 for `x` and `y`:

# Generate random integers for x and y
set.seed(123)  # Setting a seed for reproducibility
x <- floor(runif(1000, min = 0, max = 2))  # 0 or 1
y <- floor(runif(1000, min = 0, max = 2))  # 0 or 1

# Create a data frame
d <- data.frame(x = x, y = y)

# Generate a grouping variable
d$group <- as.factor(sample(LETTERS[1:2], 1000, replace = TRUE, prob = c(0.8, 0.2)))


In this code:

1. We use `floor(runif(...))` to generate random integers. `runif` generates random numbers between 0 and 2 (exclusive), and `floor` rounds them down to either 0 or 1.

2. We set a seed using `set.seed(123)` for reproducibility so that you can get the same random numbers if you run the code again.

3. We create a data frame `d` with columns `x`, `y`, and `group`.

Now, `x` and `y` should contain random integers 0 or 1, and `group` will contain random letters from `LETTERS[1:2]` with the specified probabilities.

Unlock the power of data and embark on a journey towards becoming a skilled data scientist. Join our comprehensive Data Science Training program today!

answered Sep 8, 2023 by anonymous
• 1,420 points