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)
|
> names <- c("John", "Mary")
> for (i in 1:length(names)) print(names[i])
|
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)
|
> for (i in seq_along(names)) print(names[i])
|
These functions return an empty object (length(0)) if
n is 0 or if names is empty:
> for (i in seq_len(0)) print(i)
> names <- NULL
> seq_along(names)
|
> 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