R:样本函数重复相同的结果

时间:2018-07-10 06:25:57

标签: r random sample mersenne-twister

我遇到sample()很奇怪的事情。如果在会话开始时(在RStudio或R中)运行5行以下代码,则会得到以下结果。

sample(letters,5,replace=TRUE)
[1] "b" "y" "d" "p" "n"
[1] "v" "n" "i" "s" "s"
[1] "d" "q" "a" "m" "x"
[1] "w" "s" "u" "h" "e"
[1] "b" "y" "g" "s" "e"

但是,如果我重新启动控制台并在新会话开始时运行5次,每次都会得到相同的结果。 sample()(我相信默认情况下使用Mersenne Twister)是否应该这样做?我应该怎么做才能获得实际上不会重复的结果?

1 个答案:

答案 0 :(得分:1)

set.seed(123)
> sample(letters,5,replace=TRUE)
[1] "h" "u" "k" "w" "y"
> sample(letters,5,replace=TRUE)
[1] "b" "n" "x" "o" "l"
> sample(letters,5,replace=TRUE)
[1] "y" "l" "r" "o" "c"
> sample(letters,5,replace=TRUE)
[1] "x" "g" "b" "i" "y"
> sample(letters,5,replace=TRUE)
[1] "x" "s" "q" "z" "r"

如果开始新的会话并更改set.seed的值,则会得到不同的结果。

> set.seed(456)

> sample(letters,5,replace=TRUE)
[1] "c" "f" "t" "w" "u"
> sample(letters,5,replace=TRUE)
[1] "i" "c" "h" "g" "k"
> sample(letters,5,replace=TRUE)
[1] "j" "f" "t" "v" "p"
> sample(letters,5,replace=TRUE)
[1] "q" "v" "l" "s" "h"
> sample(letters,5,replace=TRUE)
[1] "e" "s" "x" "l" "v"

希望有帮助。