Skip to content

Sum of Probabilities in a matrix...

3 messages · Jim Silverton, Dennis Murphy, Rolf Turner

#
Let's make it a data frame instead:

# Read the data from your post into a data frame named d:
d <- read.table(textConnection("
0.98   2
0.2     1
0.01   2
0.5     1
0.6     6"))
closeAllConnections()

# Use the ave() function and append the result to d:
d$sumprob <- with(d, ave(V1, V2, FUN = sum))
V1 V2 sumprob
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

HTH,
Dennis
On Sat, Oct 1, 2011 at 6:06 PM, Jim Silverton <jim.silverton at gmail.com> wrote:
#
On 02/10/11 14:06, Jim Silverton wrote:
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