6.8) Loops
To avoid repetitive commands you can sometimes use a loop. This involves the function for()
, which is normally used roughly as follows:
B <- c()
for (i in 1:length(A))
B[i] <- f(A[i])
where A
is an object with data to be processed, B
is an empty vector (c()
) created to receive the results, f()
is some function and i
is used here as an index to work through the elements in A
while we create corresponding elements in B
. This means that for each value of i
between 1 and the number of elements in A
(its length), the function is applied to the ith element of A
and the result goes into the ith element of B
. For example:
swiss.hist <- list()
for (i in 1:length(swiss))
swiss.hist[[i]] <- hist(swiss[[i]], plot=FALSE)[2:5]
names(swiss.hist) <- names(swiss) # This line gives names to the result