因此,我尝试进行10个不同的引导程序仿真,样本大小分别为10,20,...,100。因此,我创建了一个包含这些样本大小的向量,然后使用for循环对其进行迭代,如下所示。
while循环仅计算引导样本的平均值1800次,并将所有这些值存储在向量K中。这意味着我应该得到10个不同的向量K,最后对于每个j,我想将每个K在矩阵L的一列中。
问题是我得到矩阵L,但是所有列都是相同的。循环有问题,我无法弄清它是什么。
任何输入表示赞赏。这是我的代码:
N = 1800
i = 0
K = vector("numeric", 1800L)
L = matrix(nrow = 1800, ncol = 10)
ListValues = c(10,20,30,40,50,60,70,80,90,100)
for (j in 1:10){
while (i <= N){
x = sample(Data, ListValues[j])
K[i] = mean(x)
i = i + 1
}
L[,j] = K
}
print(L)
结果:
> print(L)
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[1,] 3.669182 3.669182 3.669182 3.669182 3.669182 3.669182 3.669182 3.669182 3.669182 3.669182
[2,] 3.764834 3.764834 3.764834 3.764834 3.764834 3.764834 3.764834 3.764834 3.764834 3.764834
[3,] 4.324697 4.324697 4.324697 4.324697 4.324697 4.324697 4.324697 4.324697 4.324697 4.324697
[4,] 4.473386 4.473386 4.473386 4.473386 4.473386 4.473386 4.473386 4.473386 4.473386 4.473386
答案 0 :(得分:3)
这是一个简短的版本:
N <- 1800L
L <- matrix(nrow = N, ncol = 10)
ListValues <- c(10,20,30,40,50,60,70,80,90,100)
for (j in 1:10) L[,j] <- replicate(N, mean(sample(Data, ListValues[j])))
或更短(但不快):
N <- 1800L
ListValues <- c(10,20,30,40,50,60,70,80,90,100)
L <- sapply(1:10, function(j) replicate(N, mean(sample(Data, ListValues[j]))))
答案 1 :(得分:1)
尝试一下:
N = 1800
i = 0
K = vector("numeric", 1800L)
L = matrix(nrow = 1800, ncol = 10)
ListValues = c(10,20,30,40,50,60,70,80,90,100)
for (j in 1:10){
i = 0
while (i <= N){
x = sample(Data, ListValues[j])
K[i] = mean(x)
i = i + 1
}
L[,j] = K
}
print(L)