Previous: If-Statements Up: Programming Statements Next: Example 1: Creating a

For-Loops

Use for to repeat (loop) operations. Avoiding loops by using matrix or vector commands is usually faster and more elegant, but loops are sometimes necessary to assign values. If you are using a loop to assign values to a data structure, you must first initialize an empty data structure to hold the values you are assigning.

Select a data structure compatible with the type of output your loop will generate. If your loop generates a scalar, store it in a vector (with the 4#4 th value in the vector corresponding to the the 4#4 th run of the loop). If your loop generates vector output, store them as rows (or columns) in a matrix, where the 4#4 th row (or column) corresponds to the 4#4 th iteration of the loop. If your output consists of matrices, stack them into an array. For list output (such as regression output) or output that changes dimensions in each iteration, use a list. To initialize these data structures, use:

> x <- vector()                          # An empty vector of any length.
> x <- list()                            # An empty list of any length.
The vector() and list() commands create a vector or list of any length, such that assigning x[5] <- 15 automatically creates a vector with 5 elements, the first four of which are empty values (NA). In contrast, the matrix() and array() commands create data structures that are restricted to their original dimensions.
> x <- matrix(nrow = 5, ncol = 2)  # A matrix with 5 rows and 2 columns.
> x <- array(dim = c(5,2,3))       # A 3D array of 3 stacked 5 by 2 matrices.
If you attempt to assign a value at 49#49 to either of these data structures, R will return an error message (``subscript is out of bounds''). R does not automatically extend the dimensions of either a matrix or an array to accommodate additional values.



Subsections

Gary King 2011-11-29