# examples of for loops in R # Example 1, add the numbers from 1 to n cat(" Example 1, simple loop, simple summation\n\n") # two carriage returns to leave a blank line n = 6 # the number of terms to add up sum = 0 # this is "initialization", setting values at the start of a loop for( i in 1:n) { sum = sum + i cat("sum is ", sum, " and i is ", i, "\n") } cat( "Done with sum loop. ", i, " terms gave sum = ", sum, "\n") # Example 2, the construction 1:n in the for loop makes an R list with the integers (1, 2, ..., n) cat("\n Example 2, simple loop, add elements of a list\n\n") list = 1:n cat("list is ", list, "\n") list = c(3, -2, 5) cat("now, list is ", list, "\n\n") sum = 0 # you have to re-initialize, or you start with sum = 36 for( i in list) { sum = sum + i cat("sum is ", sum, " and i is ", i, "\n") } cat( "Done with sum loop, ", i, " terms gave sum = ", sum, "\n") # Example 3, break out of a loop when a condition is satisfied n = 10 target = 30 sum = 0. cat("\n Example 3, find how many terms it takes to reach sum > ", target, "\n\n") for( i in 1:n) { sum = sum + i cat("sum is ", sum, " and i is ", i, "\n") if ( sum > target) break } cat( i, " terms gave sum = ", sum, "\n") # Example 4, a different test in the loop target = 30 sum = 0. cat("\n Example 4, a different test in the loop ", target, "\n\n") for( i in 1:n) { if ( sum > target) { cat("above the target. sum is ", sum, " and i is ", i, "\n") } else{ sum = sum + i cat("below the target, sum is ", sum, " and i is ", i, "\n") } } cat( i, " terms gave sum = ", sum, "\n") # Example 5, approximate an integral cat("\n Example 5, approximate an integral\n\n") # Estimate the integral of e^x in the range 0 < x < L # Use n rectangles of size dx = L/n n = 1000 # Don't "hard wire" variables in a program that you might ... L = 3 # ... want to change later. dx = L/n # The width of a rectangle # Initialization x = 0 # x will be the point at the left end of an interval TotalArea = 0 # the integration loop for( i in 1:n) { RectangleArea = dx*exp(x) # The area of this little rectanble TotalArea = TotalArea + RectangleArea # Add in the area of this rectangle x = x + dx # Increment x to be the left end of the next interval # cat("i = ", i, ", and x = ", x, "\n") # for debugging, comment this out for production runs } cat("Integrate from 0 to ", L, " using ", n, " points. Get ", TotalArea,"\n") ans = exp(L)-1 err = TotalArea - ans cat("The exact answer is ", ans, " and the error is ", err, "\n\n")