R语言|生成随机数

2021-09-12  本文已影响0人  生信频道

首先,如果想要别人复现出跟你一样的结果,要先设置随机种子
Set the seed of R‘s random number generator, which is useful for creating simulations or random objects that can be reproduced.

主要作用:可重现一样的结果

set.seed(123)
Generate a random number

If you want to generate a decimal number where any value (including fractional values) between the stated minimum and maximum is equally likely, use the runif function.

# generate one random number between 5.0 and 7.5:
> x1 <- runif(1, 5.0, 7.5)
> x1
[1] 6.715697
Generate a random integer
> x3 <- sample(1:10, 1)
> x3
[1] 4

The first argument is a vector of valid numbers to generate (here, the numbers 1 to 10), and the second argument indicates one number should be returned.

If we want to generate more than one random number, we have to add an additional argument to indicate that repeats are allowed:

> x4 <- sample(1:10, 5, replace=T)
> x4
[1] 6 9 7 6 5
上一篇 下一篇

猜你喜欢

热点阅读