[R] seq_len
Joe W. Byers
ecjbosu at aol.com
Sun Dec 9 19:51:45 CET 2007
Charilaos Skiadas wrote:
>
> On Dec 8, 2007, at 1:02 AM, Joe W. Byers wrote:
>
>> In a post on R-devel, Prof Ripley add the following comment
>> | > BTW, 1:dim(names)[1] is dangerous: it could be 1:0. That was the
>> | > motivation for seq_len.
>>
>> I use the dim(names)[1] and dim(x)[2] along with length(x) with varying
>> levels of frustration depending on the object which I am trying to get
>> the dimensions. I found the reference to seq_len interesting since it
>> is a function that I have never seen (probably just missed it reading
>> the docs).
>>
>> I was hoping someone could expand on the benefits of seq_len.
>
> I think that example says it all. But in simpler form, suppose x is a
> vector, and you want to produce a regular sequence of integers of the
> same length. What should happen i the vector x has length 0? Here's
> the output of the two commands.
>
> x<-numeric(0)
> > y<-length(x)
> > y
> [1] 0
> > 1:y
> [1] 1 0
> > seq_len(y)
> integer(0)
>
> Other than treating the edge case correctly, the only other advantage
> of seq_len, that I am aware of, is that it is faster. Not sure how
> often that ends up mattering though.
>
>> Happy Holidays
>> Joe
>>
>
> Haris Skiadas
> Department of Mathematics and Computer Science
> Hanover College
>
>
>
>
The essence of this feature is to get the correct index sequences when
performing matrix lookups and loops without causing errors in the
matrices or subscripts. If I build the correct x=seq_len or
x=seq(along=) and use the 'in x' not 'in 1:dim(x)[1]' or 'in
1:length(x)', my code will execute correctly without the NA/NAN error or
subscript out of bounds, etc. Is this correct?
Examples
> x=numeric()
> x
numeric(0)
> for ( i in 1:x) print(i)
Error in 1:x : NA/NaN argument
> for ( i in x) print(i)
> x=2
> for ( i in x) print(i)
[1] 2
> seq_len(x)
[1] 1 2
> x=seq_len(x)
> for ( i in x) print(i)
[1] 1
[1] 2
> for ( i in 1:x) print(i)
[1] 1
Warning message:
In 1:x : numerical expression has 2 elements: only the first used
> for ( i in x) print(i)
[1] 1
[1] 2
> x=2
> for ( i in 1:x) print(i)
[1] 1
[1] 2
> for ( i in x) print(i)
[1] 2
> for (i in 1:length(x)) print(i)
[1] 1
>
Thank you
Joe
More information about the R-help
mailing list