[R] A matrix problem

Richard M. Heiberger rmh at temple.edu
Sat Aug 19 22:10:21 CEST 2006


> 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