> x <- matrix(c(1,5,2,1,3,1,1,5), ncol=2)
>
> x
     [,1] [,2]
[1,]    1    3
[2,]    5    1
[3,]    2    1
[4,]    1    5
> (y <- tapply(x[,2], x[,1], sum))
1 2 5
8 1 1
> result <- numeric(max(as.numeric(names(y))))
> result
[1] 0 0 0 0 0
> result[as.numeric(names(y))] <- y
> result
[1] 8 1 0 0 1
>


On 8/19/06, Atte Tenkanen <[EMAIL PROTECTED]> wrote:
>
> Hi,
>
> I have a matrix with two columns. The first column means "indexes", the
> second one contents of those indexes. If I have a MATRIX like this,
>
> > MATRIX
>     [,1] [,2]
> [1,]    1    3
> [2,]    5    1
> [3,]    2    1
> [4,]    1    5
>
> I'd like to get as a result vector the sums of these indexes, something
> like this:
>
> > c(8,1,0,0,1)
>
> How to do this?
>
> I did solved it this way, but is there some more elegant way:
>
> RESULTVECTOR=c();
> RESULTMATRIX=c();
> INDEXES=as.integer(names(table(TRANSP_TABLE[,1])));
>
> for(i in INDEXES)
> {
>        RESULTVECTOR=c(i,sum(MATRIX[,2][MATRIX[,1]==i]))
>        RESULTMATRIX=rbind(RESULTMATRIX,RESULTVECTOR)
> }
> row.names(RESULTMATRIX)<-INDEXES;
> RESULTMATRIX=RESULTMATRIX[,2];
>
> > RESULTMATRIX
> 1 2 5
> 8 1 1
>
>
> Atte Tenkanen
> University of Turku, Finland
>
> ______________________________________________
> [email protected] 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.
>



-- 
Jim Holtman
Cincinnati, OH
+1 513 646 9390

What is the problem you are trying to solve?

        [[alternative HTML version deleted]]

______________________________________________
[email protected] 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.

Reply via email to