这些功能在任何方面都不相等。
1。类型
f1() 输出一个向量,f2() 输出一个矩阵。
正如@RicS 所说,第一个返回一个向量,第二个返回一个矩阵。
2。时间
f1() 几乎是 f2() 的 50 倍。
运行时的差异在更大范围内变得更加清晰:
set.seed(1701)
# Functions
f1 <- function() { sample(rep(1:4, 10000)) }
f2 <- function() { c(replicate(10000, sample(1:4))) }
# Benchmark
microbenchmark::microbenchmark(f1(), f2())
Unit: microseconds
expr min lq mean median uq max neval cld
f1() 671.28 820.6755 983.9417 988.7985 1046.476 2320.425 100 a
f2() 40588.03 43241.0270 48796.0141 45612.0740 54431.890 71117.415 100 b
我们看到f1() 明显更快,正如@JosephClarkMcIntyre 在 cmets 中所说的那样。
但它们的随机性至少是相等的吗?
让我们测试一下!
3。随机性
f2() 不是随机的。
Bartels 秩检验可以测试一系列数字的随机性与非随机性。
> randtests::bartels.rank.test(as.numeric(f1_result$value))
Bartels Ratio Test
data: as.numeric(f1_result$value)
statistic = -1.26, n = 40000, p-value = 0.2077
alternative hypothesis: nonrandomness
p 值 > 0.05,因此没有拒绝原假设。
f1() 的结果不是非随机的。 (这和确定是随机的不一样)
> randtests::bartels.rank.test(as.numeric(f2_result$value))
Bartels Ratio Test
data: as.numeric(f2_result$value)
statistic = 50.017, n = 40000, p-value < 2.2e-16
alternative hypothesis: nonrandomness
p 值 f1() 的结果是非随机的。
如果您查看函数本身的结果,这一点也很明显。
> set.seed(1701)
> replicate(10, sample(1:4))
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[1,] 1 4 1 3 3 2 3 3 4 1
[2,] 3 1 2 1 4 3 2 2 3 4
[3,] 4 2 3 2 1 1 4 4 2 2
[4,] 2 3 4 4 2 4 1 1 1 3
它产生一个有十列的矩阵,每列包含正好的数字 1:4。这不是随机的。