Togaware DATA MINING
Desktop Survival Guide
by Graham Williams
Google

For Loop

Sequences are often used in for loops, and often the sequence will be based on a variable:



> n <- 2
> for (i in 1:n) print(i)



[1] 1
[1] 2



> names <- c("John", "Mary")
> for (i in 1:length(names)) print(names[i])



[1] "John"
[1] "Mary"

In both cases we may get unexpected results if n is 0 or if names is NULL. Convenient alternatives to these two cases are seq_len and seq_along:



> for (i in seq_len(n)) print(i)



[1] 1
[1] 2



> for (i in seq_along(names)) print(names[i])



[1] "John"
[1] "Mary"

These functions return an empty object (length(0)) if n is 0 or if names is empty:



> n <- 0
> seq_len(n)



integer(0)



> for (i in seq_len(0)) print(i)
> names <- NULL
> seq_along(names)



integer(0)



> for (i in seq_along(names)) print(names[i])



Copyright © Togaware Pty Ltd
Support further development through the purchase of the PDF version of the book.
The PDF version is a formatted comprehensive draft book (with over 800 pages).
Brought to you by Togaware. This page generated: Sunday, 22 August 2010