[R] A matrix problem

Atte Tenkanen attenka at utu.fi
Sat Aug 19 21:38:27 CEST 2006


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



More information about the R-help mailing list