[R] seq argument along.with
Rui Barradas
ruipbarradas at sapo.pt
Sat Apr 15 12:53:03 CEST 2017
Hello,
A good example of a use case of seq_along is to avoid constructs such as
1:length(x) that don't make sense and are a source for bugs whenever x
is of length zero. See for instance loops where careless coders do
for(i in 1:length(x)){
x[i] <- some computation
}
If x is of length zero the loop above will execute 2 times but the
second time through it will throw an error because it will refer to
x[0], which is illegal.
To avoid this, use
for(i in seq_along(x)){
[...]
}
With a zero-length x, the loop will execute zero times, the intended
behaviour.
If it's the first time you've came across this function, I can guarantee
you that it is really, really usefull.
Hope this helps,
Rui Barradas
Em 15-04-2017 00:58, Carl Sutton via R-help escreveu:
> Hi Jeff
> I have seen the seq_along function but never knew the what or why of it. Your response is much appreciated and just shows how brilliant the creators of R were/are.
> Thank you for enlightening me. Carl Sutton
>
> On Friday, April 14, 2017 3:54 PM, Jeff Newmiller <jdnewmil at dcn.davis.ca.us> wrote:
>
>
> Have you ever used the seq_along() function?
>
> If you want to delegate the decision of how many elements you want to process to some earlier point in your (or someone else's) code, then the most logical way to create a result vector that is the same size as some input vector, even if that vector is of zero length, is to show that vector to the seq function as an example of how long to make the result.
>
More information about the R-help
mailing list