[R] reorganizing a data frame

Duncan Murdoch dmurdoch at pair.com
Sat Jul 8 04:04:17 CEST 2000


On Fri, 7 Jul 2000 17:17:56 -0500, "Jeff Miller" <jdm at xnet.com> wrote:

>
>Hi, 
>
>I have what I think is an easy question.
>
>I have a data frame, called stockdata, of stock prices that looks like this:
>
>
>         date       ticker       close 
> 1 01/02/1998    GE       24.667
> 2 01/05/1998    GE       25.104
> 3 01/06/1998    GE       24.771
> 4 01/07/1998    GE       24.979
> 5 01/08/1998    GE       24.750
> 6 01/02/1998    HIT       71.125
> 7 01/05/1998    HIT       72.313
> 8 01/06/1998    HIT       72.563
> 9 01/02/1998    INTC     36.313
>10 01/05/1998   INTC     37.250
>11 01/06/1998   INTC     36.563
>12 01/07/1998   INTC     36.375
>13 01/08/1998   INTC     37.156
>
>I would like to turn this data frame into a matrix, closedata, that looks like 
>this 
>                        GE         HIT          INTC 
>01/02/1998     24.667     71.125     36.313
>01/05/1998     25.104     72.313     37.250
>01/06/1998     24.771     72.563     36.563
>01/07/1998     24.979     NA          36.375
>01/08/1998     24.750     NA          37.156
>
> 
>What is the best way to do this?

The tapply() function is what you want.  I think the code would be 

tapply(INTC,list(date,ticker),INTC,mean)

This will give you the average entry in each spot in the table; if
there's more than one entry, that might not be what you want.  I don't
know how you'd tell it to list the date twice, for instance.

Duncan Murdoch
-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._



More information about the R-help mailing list