我正在尝试重复这个简单的命令10,000次(通过一个简单而容易的解决方案):
Tandem <- sample(OUT, size = 815, replace = TRUE, prob = NULL); mean(Tandem)任何建议都将不胜感激。
发布于 2013-12-31 16:27:12
您可以使用replicate或sapply
R> colMeans(replicate(10000, sample(100, size=815, replace=TRUE, prob=NULL)))
R> sapply(seq_len(10000), function(...) mean(sample(100, size=815, replace=TRUE, prob=NULL)))replicate是sapply的常用包装器,用于重复计算表达式(通常涉及随机数生成)。
发布于 2013-12-31 16:53:15
还不清楚你这样问是否是因为你是编程新手,但是如果是这样的话,你可能应该阅读this article on loops,并阅读一些关于编程的基本资料。
如果您已经了解了控制结构,并且想要了解特定于R的实现细节,那么有许多教程可供选择,例如this one。另一个答案是使用replicate和colMeans,这在用R编写时是惯用的,而且可能也很快,如果你想要10,000次迭代,这是很重要的。
但是,(对于初学者)处理这类问题的一种更通用、更直接的方法是使用for循环。
> for (ii in 1:5) {
+ print(ii)
+ }
[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
>因此,在您的示例中,如果您只想将Tandem对象的平均值打印5次:
for (ii in 1:5) {
Tandem <- sample(OUT, size = 815, replace = TRUE, prob = NULL)
TandemMean <- mean(Tandem)
print(TandemMean)
}如上所述,replicate是使用R处理此特定问题的一种更自然的方法。无论如何,如果您想要存储结果-这肯定是事实-您将需要开始考虑像vectors和lists这样的数据结构。一旦你存储了一些东西,你就需要能够访问它来在将来使用它,所以一点知识是至关重要的。
set.seed(1234)
OUT <- runif(100000, 1, 2)
tandem <- list()
for (ii in 1:10000) {
tandem[[ii]] <- mean(sample(OUT, size = 815, replace = TRUE, prob = NULL))
}
tandem[1]
tandem[100]
tandem[20:25]...creates此输出:
> set.seed(1234)
> OUT <- runif(100000, 1, 2)
> tandem <- list()
> for (ii in 1:10000) {
+ tandem[[ii]] <- mean(sample(OUT, size = 815, replace = TRUE, prob = NULL))
+ }
>
> tandem[1]
[[1]]
[1] 1.511923
> tandem[100]
[[1]]
[1] 1.496777
> tandem[20:25]
[[1]]
[1] 1.500669
[[2]]
[1] 1.487552
[[3]]
[1] 1.503409
[[4]]
[1] 1.501362
[[5]]
[1] 1.499728
[[6]]
[1] 1.492798
> https://stackoverflow.com/questions/20888215
复制相似问题