R for循环仅迭代最后一个子阵列

时间:2017-08-16 18:35:16

标签: arrays r

我编写了一个简单的例程来迭代变量,包括多个子数组,但似乎它只循环遍历最后一个子数组而不是所有数组,一次一个。

我的代码如下:

K <- 2 # number of subarrays

N <- 100

Hstar <- 20

perms <- 10000

specs <- 1:N 

pop <- array(dim = c(c(perms, N), K))

haps <- as.character(1:Hstar)

probs <- rep(1/Hstar, Hstar) 

for(j in 1:perms){

for(i in 1:K){

    pop[,, 1] <- sample(haps[1:10], size = N, replace = TRUE, prob = probs[1:10])

    pop[,, 2] <- sample(haps[11:20], size = N, replace = TRUE, prob = probs[11:20])

 }

 }

HAC.mat <- array(dim = c(perms, N))

for(k in specs){

for(j in 1:perms){

    for(i in 1:K){

        ind.index <- sample(specs, size = k, replace = FALSE)

        hap.plot <- pop[j, ind.index, i]

        HAC.mat[j, k] <- length(unique(hap.plot)) 
    }
}
}

问题似乎是在hap.plot中,它只使用pop [,, 2](子阵列2)中的标签填充,而不是来自两个子阵列的标签。我不确定为什么会这样。

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:0)

我认为您可能需要HAC.mat作为三维数组,否则HAC.mat只能在hap.plot时记录i=K

K <- 2 # number of subarrays
N <- 100
Hstar <- 20
perms <- 10000
specs <- 1:N 
pop <- array(dim = c(c(perms, N), K))
haps <- as.character(1:Hstar)
probs <- rep(1/Hstar, Hstar)
for(j in 1:perms){
    for(i in 1:K){
        # looks like j was missing in previous code.
        pop[j,, 1] <- sample(haps[1:10], size = N, replace = TRUE, prob = probs[1:10])
        # change [11:20] to [1:20] for both haps and probs.
        pop[j,, 2] <- sample(haps[1:20], size = N, replace = TRUE, prob = probs[1:20])
    }
}
HAC.mat <- array(dim = c(c(perms, N), K)) # HAC.mat as 3-dim array
for(k in specs){
    for(j in 1:perms){
        for(i in 1:K){
            ind.index <- sample(specs, size = k, replace = FALSE)
            hap.plot <- pop[j, ind.index, i]
            HAC.mat[j, k, i] <- length(unique(hap.plot)) # record i on 3rd dim
        }
    }
}

如果有效,请告诉我们,您可以尝试perms<-10试一试,否则需要一段时间。