[R] Vector recycling and zoo

Gabor Grothendieck ggrothendieck at gmail.com
Mon May 17 01:48:36 CEST 2010


Normally that would be written like this using the coredata extraction
function which extracts the data portion of a zoo object:

x$a / coredata( x$a[1] )

On Sun, May 16, 2010 at 7:32 PM, Sean Carmody <seancarmody at gmail.com> wrote:
> Thanks David,
>
> You comment made me realise that whereas when x is a data frame, x$a is a
> numeric vector,
> when x is of class zoo, x$a is also of class zoo, so the following does what
> I was expecting:
>
> x$a/as.numeric(x$a[1])
>
> Sean.
>
> On Sun, May 16, 2010 at 9:25 PM, David Winsemius <dwinsemius at comcast.net>wrote:
>
>>
>> On May 16, 2010, at 2:00 AM, Sean Carmody wrote:
>>
>>  I am a bit confused about the different approaches taken to recycling in
>>> plain data frames and zoo objects. When carrying out simple arithmetic,
>>> dataframe seem to recycle single arguments, zoo objects do not. Here is an
>>> example
>>>
>>>  x <- data.frame(a=1:5*2, b=1:5*3)
>>>> x
>>>>
>>>  a  b
>>> 1  2  3
>>> 2  4  6
>>> 3  6  9
>>> 4  8 12
>>> 5 10 15
>>>
>>>> x$a/x$a[1]
>>>>
>>> [1] 1 2 3 4 5
>>>
>>>> x <- zoo(x)
>>>> x$a/x$a[1]
>>>>
>>> 1
>>> 1
>>>
>>>>
>>>>
>>> I feel understanding this difference would lead me to a greater
>>> understanding of the zoo module!
>>>
>>
>> I think you do have misunderstandings about the zoo package but I do not
>> think it is in the area of vector recycling. Notice the effect of your
>> application of the zoo function to x:
>>
>> > x$a
>>
>>  1  2  3  4  5
>>  2  4  6  8 10
>> > x$a[1]
>> 1
>> 2
>>
>> You have in effect transposed the elements in x and are now getting a two
>> element column vector when requesting x$a[1].  The term vector recycling is
>> applied to situations where short vectors are reused starting with their
>> first elements until the necessary length is achieved. For instance if you
>> request:
>>
>> > data.frame(x=1:2, y=letters[1:10])
>>   x y
>> 1  1 a
>> 2  2 b
>> 3  1 c
>> 4  2 d
>> 5  1 e
>> 6  2 f
>> 7  1 g
>> 8  2 h
>> 9  1 i
>> 10 2 j
>>
>> Or plot(1:10, col=c("red","green"))
>>
>>
>>> Sean.
>>>
>>> --
>>> Sean Carmody
>>>
>>
>>
>>
>
>
> --
> Sean Carmody
> Twitter: http://twitter.com/seancarmody
> Stable: http://mulestable.net/sean
>
> The Stubborn Mule
> Blog: http://www.stubbornmule.net
> Forum: http://mulestable.net/
>
>        [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>



More information about the R-help mailing list