開始使用免費開始

撰寫一個簡單的 for 迴圈

來寫一個 for 迴圈,把同一個流程重複多次,並把結果逐步存進一個向量。我們會使用前一個練習中建立的函式來擲骰子。

本練習屬於課程

R 的機率謎題

檢視課程

練習說明

  • for 迴圈中指定索引從 1 到 10000。
  • 填入 output 的索引,將每次的結果存起來。
  • 填入 roll_dice 的引數,讓它擲兩顆骰子。

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

# Initialize a vector to store the output
output <- rep(NA, 10000)

# Loop for 10000 iterations
for(i in ___){
  # Fill in the output vector with the result from rolling two dice
  output[___] <- roll_dice(___)
}
編輯並執行程式碼