繁体   English   中英

R:使用“floor”和“runif”生成随机数

[英]R: Generate Random Numbers with "floor" and "runif"

我正在使用 R 编程语言。 我正在尝试生成 1 到 0 之间的随机整数。使用以下链接( http://www.cookbook-r.com/Numbers/Generating_random_numbers/ ),我尝试使用此代码生成 0 到 1 之间的 1000 个随机整数:

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 的值。

有谁知道我做错了什么? 谢谢

要生成01的随机integer数字,您可以使用rbinomsample

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 ...

如果您只有01 ,最好使用只允许TRUEFALSE逻辑向量。

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

?floor

floor 接受单个数字参数 x 并返回一个数字向量,其中包含不大于 x 的相应元素的最大整数。

让我们看一个例子来理解这一点 -

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

floor总是向下舍入到最接近的 integer。 在您的示例中,使用runif您正在生成 0 和 1 之间的数字,并且由于您使用的是floor ,所有数字都向下舍入为 0,因此您只能得到 0 作为 output。

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

在 runif 中 min 和 max 的默认值是 0 和 1。 round()入到最接近的 integer。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM