2017-08-07 52 views
-1

我有變量賦值用於循環迭代在多個子陣列

N <- 10 

H <- 10 

K <- 2 # number of subarrays 

perms <- 10 

我建立一個空數組如下:

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

然後我分配字符標籤:

haps <- as.character(1:H) 

現在,我分配概率:

probs <- rep(1/H, H) 

我再創建一個「for」循環:

for(j in 1:perms){ 

    for(i in 1:K){ 
    pop[i,j] <- sample(haps, size = N, replace = TRUE, prob = probs) 
    } 
} 

「流行」現在應該包含字符標籤從跨兩個子陣列1:H。相反,我最終會得到一個錯誤「矩陣上的下標數量不正確」。

我不知道爲什麼R會產生錯誤。

任何援助表示讚賞。

回答

0

你給了3個下標向量3維向量pop。即使您添加了第三個下標,因爲該順序錯誤,樣本的尺寸也不會匹配pop切片的尺寸。

dim(pop) 

[1] 10×10×

你可能想要這個:

for(j in 1:perms){ 

    for(i in 1:K){ 
    pop[1:10,j,i] <- sample(haps, size = N, replace = TRUE, prob = probs) 
    } 

} 

pop 
, , 1 

     [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] 
[1,] "6" "8" "8" "6" "3" "3" "1" "9" "7" "8" 
[2,] "7" "10" "5" "3" "7" "10" "7" "1" "5" "8" 
[3,] "9" "7" "1" "4" "1" "3" "2" "7" "6" "5" 
[4,] "6" "8" "9" "4" "9" "7" "10" "9" "7" "2" 
[5,] "1" "3" "2" "6" "10" "3" "3" "9" "10" "6" 
[6,] "9" "3" "8" "1" "6" "6" "4" "8" "8" "9" 
[7,] "9" "2" "2" "2" "3" "9" "8" "6" "10" "10" 
[8,] "9" "5" "3" "8" "3" "4" "1" "6" "8" "4" 
[9,] "10" "8" "1" "3" "10" "2" "5" "10" "6" "4" 
[10,] "2" "1" "8" "10" "5" "5" "7" "8" "7" "6" 

, , 2 

     [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] 
[1,] "1" "10" "10" "7" "3" "6" "3" "2" "4" "1" 
[2,] "8" "5" "10" "8" "3" "6" "6" "6" "8" "2" 
[3,] "1" "6" "1" "5" "6" "3" "6" "1" "7" "9" 
[4,] "7" "10" "5" "5" "7" "5" "3" "3" "10" "1" 
[5,] "7" "3" "6" "8" "3" "9" "6" "2" "7" "3" 
[6,] "1" "9" "4" "9" "1" "1" "10" "4" "3" "9" 
[7,] "9" "3" "10" "1" "2" "2" "2" "3" "5" "4" 
[8,] "8" "10" "8" "6" "9" "6" "9" "9" "2" "4" 
[9,] "4" "6" "1" "1" "6" "5" "6" "6" "10" "3" 
[10,] "5" "9" "9" "7" "9" "6" "4" "2" "10" "9" 

雖然要覺得奇怪,我數字在haps因此pop是字符,但我認爲你有你的理由。

這是樣本的按列分配。我不知道它是否重要,但是如果你更喜歡按行排序,那麼你可以做這樣的索引:

pop[j,1:10,i] 
+0

我覺得'perm'是第一個indice。應該是'pop [j,,i]'。嘗試更改'perm' – cderv

+0

@cderv對,我只是將其作爲一個選項添加(逐行採樣)。在這個例子中,它是按列還是按行來處理並不重要,但取決於他可能想要的實際問題的上下文。 –

+0

@ Hack-R這正是我一直在尋找的! –