Skip to content

A matrix problem

2 messages · Atte Tenkanen, jim holtman

#
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,
[,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:
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];
1 2 5 
8 1 1 


Atte Tenkanen
University of Turku, Finland