Skip to content
Back to formatted view

Raw Message

Message-ID: <52B62935.50909@gmail.com>
Date: 2013-12-21T23:50:13Z
From: Duncan Murdoch
Subject: seq_len and loops
In-Reply-To: <52B61CE0.10805@umu.se>

On 13-12-21 5:57 PM, G?ran Brostr?m wrote:
> I was recently reminded on this list that
>
> "Using 1:ncol() is bad practice (seq_len is designed for that purpose)"
> (Ripley)
>
> This triggers the following question: What is "good practice" for
> 2:ncol(x)? (This is not a joke; in a recursive situation it often makes
> sense to perform the calculation for the start value i = 1, then
> continue with a loop over the rest, "the Fortran way";)
>
> I usually use
>
> if (ncol(x) > 1)
>       for (i in 2:ncol(x)){
>          ....
>
> but I can think of
>
> for (i in seq_len(x - 1)){
>       I <- i + 1
>      ....
>
> and
>
> i <- 1
> while (i < ncol(x)){
>       i <- i + 1
>       ....
>
> What is "good practice" (efficient and safe)?

for (i in seq_len(x - 1) + 1)

should be efficient and safe.  A little less efficient, but clearer would be

for (i in seq_len(x)[-1])

Duncan Murdoch