[R] Behavior of seq with vector from

Ben Bolker bolker at ufl.edu
Fri May 22 04:32:13 CEST 2009




Rowe, Brian Lee Yung (Portfolio Analytics) wrote:
> 
> Hello,
> 
> I want to use seq with multiple from values and am getting unexpected
> (to me) behavior. I'm wondering if this behavior is intentional or not.
> 
>> seq(2, by=3, length.out=4)
> [1]  2  5  8 11
> 
>> seq(3, by=3, length.out=4)
> [1]  3  6  9 12
> 
> Now if I want the combined sequence, I thought I could pass in c(2,3),
> and I get:
>> seq(c(2,3), by=3, length.out=8)
> [1]  2  6  8 12 14 18 20 24
> 
> However, the result is not what I expected (i.e. what I wanted):
> [1]  2  3  5  6  8  9 11 12
> 
> It seems that this is a consequence of vector recycling during the
> summation in seq.default:
>   if (missing(to)) from + (0L:(length.out - 1L)) * by
> 
> To get the value I want, I am using the following code:
>> sort(as.vector(apply(array(c(2,3)), 1, seq, by=3,length.out=4)))
> [1]  2  3  5  6  8  9 11 12
> 
> So two questions:
> 1. Is seq designed/intended to be used with a vector from argument, and
> is this the desired behavior?
> 2. If so, is there a cleaner way of implementing what I want?
> 
> Thanks,
> Brian
> 
> 

Don't know if this is "cleaner" or not.
It may be a little bit too tricky.

c(outer(2:3,seq(0,by=3,length.out=4),"+"))

  Can compress your example slightly:

c(t(apply(matrix(2:3), 1, seq, by=3,length.out=4)))

-- 
View this message in context: http://www.nabble.com/Behavior-of-seq-with-vector-from-tp23658790p23663549.html
Sent from the R help mailing list archive at Nabble.com.




More information about the R-help mailing list