[R] A matrix problem

Atte Tenkanen attenka at utu.fi
Sat Aug 19 23:44:35 CEST 2006


Thanks for both, tapply seems to be a fast and delicate solution. I had appr. 150 000 rows and it took few seconds to get the result. Till now I have been too tied by for-loops. I will make acquaintance with "An Introduction to R".

Atte

----- Original Message -----
From: "Richard M. Heiberger" <rmh at temple.edu>
Date: Saturday, August 19, 2006 11:10 pm
Subject: Re: [R] A matrix problem

> > x <- cbind(index=c(1,5,2,1), contents=c(3,1,1,5))
> > x
>     index contents
> [1,]     1        3
> [2,]     5        1
> [3,]     2        1
> [4,]     1        5
> 
> ## use tapply to get the values you want
> > z0 <- tapply(x[,"contents"], x[,"index"], sum)  ## read ?tapply
> > z0
> 1 2 5 
> 8 1 1 
> 
> ## more work is needed to get them into the structure you want
> > r <- range(x[,"index"])
> > r
> [1] 1 5
> > nn <- seq(r[1], r[2])
> > nn
> [1] 1 2 3 4 5
> > z <- nn*0
> > z
> [1] 0 0 0 0 0
> > names(z) <- nn
> > z
> 1 2 3 4 5 
> 0 0 0 0 0 
> > z[names(z0)] <- z0  ## read about subscripting  ?"["
> > z
> 1 2 3 4 5 
> 8 1 0 0 1 
> > 
> 
> 
> ## R is a matrix and vector language.  Loops are rarely needed.
> ## Read "An Introduction to R".
> ## It is clickable from the Help menu in the Windows RGui Console.
> ## It is available in R-2.3.1/doc/manual/R-intro.pdf on all platforms.
> 
> 
> 
> This is essentially the same as jim holtman's answer.  I did some 
> extra work
> to get nice names on the result vector.
>



More information about the R-help mailing list