[R] better code?
Spencer Graves
spencer.graves at pdf.com
Sun Jun 26 19:56:06 CEST 2005
Hi, Laura:
How about the following:
> sapply(x1.df, class)
d x y
"factor" "numeric" "numeric"
> (byLH <- by(x1.df[-1], x1.df$d, var))
x1.df$d: 1/1/2005
x y
x 1.272688 -0.783719
y -0.783719 0.884866
-------------------------------------------------------------
x1.df$d: 1/15/2005
x y
x 0.9992097 0.8719848
y 0.8719848 0.7753879
-------------------------------------------------------------
x1.df$d: 1/22/2005
x y
x 1.2269211 -0.8694323
y -0.8694323 0.6161053
-------------------------------------------------------------
x1.df$d: 1/29/2005
x y
x 0.072721473 0.006551483
y 0.006551483 1.003923812
-------------------------------------------------------------
x1.df$d: 1/8/2005
x y
x 1.4893139 0.2845754
y 0.2845754 0.6273839
spencer graves
Laura Holt wrote:
> Hi R!
>
> I have a data.frame with dates in the first column and numeric values in
> columns 2 -3.
>
> I want to have a covariance matrix for each date. The following code
> works fine:
>
>> x1.df
>
> d x y
> 1 01/01/05 1.06014788 0.72595670
> 2 01/01/05 -1.56330741 2.44930531
> 3 01/01/05 -0.58001696 0.48626682
> 4 01/01/05 0.27653308 0.52676239
> 5 01/08/05 1.91849382 1.72136239
> 6 01/08/05 -0.74774661 0.16657346
> 7 01/08/05 0.18505727 1.33570129
> 8 01/08/05 1.47015895 1.59666054
> 9 01/08/05 -0.67119562 2.31980255
> 10 01/15/05 0.39728456 2.48849586
> 11 01/15/05 -0.96484152 1.47565372
> 12 01/15/05 -1.55109398 0.73436620
> 13 01/22/05 -1.36172373 1.12015635
> 14 01/22/05 0.20475072 0.01010656
> 15 01/29/05 -0.49909855 0.15583279
> 16 01/29/05 -0.07834782 0.99454434
> 17 01/29/05 0.12845272 0.09605443
> 18 01/29/05 -0.44926053 1.48959860
> 19 01/29/05 -0.07033900 2.50253296
>
>> for(i in 1:5) {
>
> + yy <- x1.df$d == u3[i]
> + zz <- cov(x1.df[yy,2:3])
> + print(dates(u3[i]))
> + prmatrix(zz)
> + }
> [1] 01/01/05
> x y
> x 1.272688 -0.783719
> y -0.783719 0.884866
> [1] 01/08/05
> x y
> x 1.4893139 0.2845754
> y 0.2845754 0.6273839
> [1] 01/15/05
> x y
> x 0.9992097 0.8719848
> y 0.8719848 0.7753879
> [1] 01/22/05
> x y
> x 1.2269211 -0.8694323
> y -0.8694323 0.6161053
> [1] 01/29/05
> x y
> x 0.072721473 0.006551485
> y 0.006551485 1.003923812
>
>>
> However, I'm sure that there is a MUCH better way to accomplish this task.
>
> Any suggestions, please?
>
> R V 2.1.0 Windows
>
> Thank you in advance!
> Sincerely,
> Laura Holt
> mailto: lauraholt_983 at hotmail.com
>
> _________________________________________________________________
> On the road to retirement? Check out MSN Life Events for advice on how
> to get there! http://lifeevents.msn.com/category.aspx?cid=Retirement
>
--
Spencer Graves, PhD
Senior Development Engineer
PDF Solutions, Inc.
333 West San Carlos Street Suite 700
San Jose, CA 95110, USA
spencer.graves at pdf.com
www.pdf.com <http://www.pdf.com>
Tel: 408-938-4420
Fax: 408-280-7915
More information about the R-help
mailing list