[R] Column of probabilities

David Winsemius dwinsemius at comcast.net
Fri Aug 26 23:12:59 CEST 2011


On Aug 26, 2011, at 4:58 PM, David Winsemius wrote:

>
> On Aug 26, 2011, at 2:35 PM, Jim Silverton wrote:
>
>> H all,
>>
>> I have a 6 x 3 matrix. The last column is simply the sum of of the  
>> first two
>> rows.
>>
>> x1  x2   x3
>> 1     2    3
>> 2     1    3
>> 1     0    1
>> 2     2    4
>> 2     1    3
>> 2     1    3
>> 0     0    0
>>
>> I want to create a column of probabilities p, such that for each  
>> row, I want
>> to find the probability of x1=k and x3 = n divided by the  
>> probability that
>> x3 = n.
>> So I should end up with a column of probabilities:
>> 1/4, 3/4, 1/7, 1/7, 3/4, 3/4, 1/7
>
> Probabilities of what? Those don't sum to 1 together or in any sub  
> aggregation I can construct.

I suppose I ought not to drag out the torture and instead  say what I  
_think_ Jim was asking for, namely the within x3 groupings of   
conditional probabilities for x1 which he incorrectly specified.  
Assuming a dataframe named "dat":

 > dat$x3lens <- ave(dat$x3, dat$x3,           FUN = length)
 > dat$x1x3lens <- ave(dat$x3, dat$x1, dat$x3, FUN = length)
 > dat$probs <- with(dat, x1x3lens/x3lens)
 > dat
   x1 x2 x3 x3lens x1x3lens probs
1  1  2  3      4        1  0.25
2  2  1  3      4        3  0.75
3  1  0  1      1        1  1.00
4  2  2  4      1        1  1.00
5  2  1  3      4        3  0.75
6  2  1  3      4        3  0.75
7  0  0  0      1        1  1.00



-- 

David Winsemius, MD
West Hartford, CT



More information about the R-help mailing list