R:使用 "floor" 和 "runif" 生成随机数
R: Generate Random Numbers with "floor" and "runif"
我正在使用 R 编程语言。我正在尝试生成 1 到 0 之间的随机整数。使用以下 link (http://www.cookbook-r.com/Numbers/Generating_random_numbers/),我尝试使用此代码生成 1000 个 0 到 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)
但是,“x”和“y”的值似乎都只有 0。
有谁知道我做错了什么?
谢谢
来自?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.
让我们看一个例子来理解这一点-
floor(c(5.3, 9.9, 6.5, 1.2))
[1] 5 9 6 1
floor
总是向下舍入到最接近的整数。在您的示例中,使用 runif
您生成的数字介于 0 和 1 之间,并且由于您使用的是 floor
所有数字都向下舍入为 0 因此您只能得到 0 作为输出。
要生成 整数 个 0
或 1
的随机数,您可以使用 rbinom
或 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 ...
如果你只有 0
和 1
也许最好使用 逻辑 向量只允许 TRUE
和 FALSE
.
x <- sample(c(TRUE, FALSE), 1000, TRUE)
str(x)
# logi [1:1000] TRUE TRUE TRUE FALSE TRUE FALSE ...
round(stats::runif(1000), digits = 0)
在runif中,min和max的默认值是0和1。 round()
四舍五入到最接近的整数。
我正在使用 R 编程语言。我正在尝试生成 1 到 0 之间的随机整数。使用以下 link (http://www.cookbook-r.com/Numbers/Generating_random_numbers/),我尝试使用此代码生成 1000 个 0 到 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)
但是,“x”和“y”的值似乎都只有 0。
有谁知道我做错了什么? 谢谢
来自?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.
让我们看一个例子来理解这一点-
floor(c(5.3, 9.9, 6.5, 1.2))
[1] 5 9 6 1
floor
总是向下舍入到最接近的整数。在您的示例中,使用 runif
您生成的数字介于 0 和 1 之间,并且由于您使用的是 floor
所有数字都向下舍入为 0 因此您只能得到 0 作为输出。
要生成 整数 个 0
或 1
的随机数,您可以使用 rbinom
或 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 ...
如果你只有 0
和 1
也许最好使用 逻辑 向量只允许 TRUE
和 FALSE
.
x <- sample(c(TRUE, FALSE), 1000, TRUE)
str(x)
# logi [1:1000] TRUE TRUE TRUE FALSE TRUE FALSE ...
round(stats::runif(1000), digits = 0)
在runif中,min和max的默认值是0和1。 round()
四舍五入到最接近的整数。