Search code examples
rprobabilityprobability-theory

Conditional Probability with binary variables


I have this set:

    1 2 3 4
r01 1 0 1 1
r02 1 1 0 1
r03 0 0 1 0
r04 0 0 1 0

The code:

initial <- data.frame(c(1,1,0,0), c(0,1,0,0), c(1,0,1,1),c(1,1,0,0), row.names = c("r01","r02","r03","r04"))
colnames(initial) <- c(1:4)

I need to get conditional probability, for example if I choose r03 as choosen object probability conditional table with r01 will be:

          |r03=0 |r03=1
    r01=0 | 1/3  | 0/1
    r01=1 | 2/3  | 1/1

Other example, if I choose r03 and evaluate r02:

          |r03=0 |r03=1
    r02=0 | 0/3  | 1/1
    r02=1 | 3/3  | 0/1

I don't know how to implement this table or just get this matrix values.


Solution

  • I think that you are looking for this:

    initial <- data.frame(c(1,1,0,0), c(0,1,0,0), c(1,0,1,1),c(1,1,0,0), row.names = c("r01","r02","r03","r04"))
    colnames(initial) <- c(1:4)
    
    tin <- data.frame(matrix(t(initial), ncol = 4, byrow = FALSE))
    colnames(tin) <- rownames(initial)
    
    tab <- table(tin$r01, tin$r03) #here specify values and get count
    prop.table(tab,2)
    

    You also can add some rownames i colnames

    EDIT: Fixed probability and created matrix by columns