


# for loops are truly valuable when the calculation is more complicated and we can't do it exactly or with built in R functions. Mean(trials^2) 15.207 # Of course we could have done this simulation without a loop. Trials = sample(1:nsides,1) # We get one sample at a time

Sum(x) class='r'> 338350 # Let's use a for loop to estimate the average of squaring the result of a roll of a die. X class='r'> 1 4 9 16 25 # You always wanted to know the sum of the first 100 squares. # First we create a vector and then we fill in its values n = 5 25 # We can capture the results of our loop in a list # Loop through the sequence 1 to 5 printing the square of each number for (j in 1:5) X 1 2 3 4 1 2 3 4 1 2 3 4 1 2 3 4 1 2 3 4 for(i in x) # 'for loops' let us repeat (loop) through the elements in a vector and run the same code on each element X 0 0 0 0 0 0 0 0 0 0 # rep() will replicate almost anything x = rep(2,6) # rep(0, 10) makes a vector of of 10 zeros. R makes this easy with the replicate function rep() This is a short tutorial to explain 'for loops'.Ĭolor coding # Comments are in maroon Code is in black Results are in this green rep() # Often we want to start with a vector of 0's and then modify the entries in later code.
