On 02/10/11 14:06, Jim Silverton wrote:
Hi all,
I have 2 columns in a mtrix, one of which is a column of probabilities and
the other is simply a vector of integers. I want to sum all the
probabilities with the same integer value and put it in a new column.
For example,
If my matrix is:

0.98   2
0.2     1
0.01   2
0.5     1
0.6     6


Then I should get:
0.98   2    0.99
0.2     1    0.70
0.01   2    0.99
0.5     1    0.70
0.6     6    0.60

Any help is greatly appreciated.

Suppose your matrix is called "m".  Execute:

> ttt <- tapply(m[,1],m[,2],sum)
> m <- cbind(m,ttt[match(m[,2],names(ttt))])
> dimnames(m) <- NULL # To tidy up a bit.

You get:
> m
     [,1] [,2] [,3]
[1,] 0.98    2 0.99
[2,] 0.20    1 0.70
[3,] 0.01    2 0.99
[4,] 0.50    1 0.70
[5,] 0.60    6 0.60

Easy-peasy.

    cheers,

        Rolf Turner

______________________________________________
[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