首先,如果想要别人复现出跟你一样的结果,要先设置随机种子
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
网友评论