2016-09-10 80 views
-2

我正在運行一個小循環來爲4個組的子集隨機分配一個數字列表(1到30)。我想將循環的輸出(對於4個子集)作爲一行存儲在一個變量中,並將結果存儲在別處。我也收到一些警告,雖然輸出正確顯示在屏幕上。將循環中的輸出存儲爲R中的列表

list = as.vector(c(6, 9, 3, 12) 
start <- 1 
end <- 6 
i <- 1 
while(i<=list){ 
    print(sample(start:end, replace=T)) 
    start <- start+list[i] 
    end <- end + list[i+1] 
    i <- i+1 
} 

[1] 3 5 6 1 5 6 
[1] 9 13 12 7 11 12 14 11 14 
[1] 16 17 17 
[1] 28 22 26 21 28 26 22 28 26 30 21 19 
Error in start:end : NA/NaN argument 
In addition: Warning messages: 
1: In while (i <= list) { : 
    the condition has length > 1 and only the first element will be used 
2: In while (i <= list) { : 
    the condition has length > 1 and only the first element will be used 
3: In while (i <= list) { : 
    the condition has length > 1 and only the first element will be used 
4: In while (i <= list) { : 
    the condition has length > 1 and only the first element will be used 
5: In while (i <= list) { : 
    the condition has length > 1 and only the first element will be used 

我無法找到此錯誤的原因。請幫忙。謝謝。

+0

'地圖(功能(啓動,停止){樣品(開始:停止,替換= TRUE)},cumsum(c(1,6,9,3)),cumsum(c(6,9,3,12)))' – alistaire

+0

我嘗試初始化'y < - NULL; temp < - sample(...),y mysqlnew

+0

感謝@alistaire的幫助。它仍然產生四行輸出。我希望單行輸出有兩個原因:(1)樣本量和分組非常大。因此,對於m x n組的單行輸出將會有所幫助。 (2)實際情況下的cumsum值會因此而大於此示例;因此,我希望指定一個列表,可以控制m x n個數據集。再次感謝。 – mysqlnew

回答

0
使用用於循環比while循環

工作得很好,沒有必要子設置變量i的當我們使用SEQ功能

list = c(6, 9, 3, 12) 
start <- 1 
end <- 6 

for(i in seq(list)){ 
    if(i <= list[i]){ 
    start <- start+list[i] 
    end <- end + (list[i]+1) 
    print(sample(start:end, replace=T)) 
    } 

} 

[1] 10 8 11 7 11 10 12 
[1] 23 17 18 21 22 18 20 21 
[1] 25 21 27 23 26 26 23 25 22 
[1] 33 32 37 37 35 40 32 37 34 38 
+0

@mysqlnew在你的列表中你有6,9,3,12當你運行一個循環子設置i = 1時,在最後一次迭代中我的值爲4,並且i = i + 1變爲5,其中5不小於或等於5在你的清單中等於3,所以你會得到錯誤信息 –

+0

感謝Arun的澄清。 for循環將是一個大樣本量的問題。 – mysqlnew

+0

@mysqlnew如果您覺得正確,請投我的答案 –