I'm trying to create a conditional probability model from the "Titanic" data in R. I get confused on the calculations once I include two or more conditions.

enter image description here

enter image description here

it is clear for me how to calculate the probability on one condition. for example: $$P(\text{Sex} = \text{"Male"} | \text{class} = \text{"crew"}) = \frac{862}{885} = 974$$

How can we calculate these two conditional probabilities?

$$P(\text{survived} = \text{"Yes"} | \text{sex} = \text{"Male"}, \text{class} = \text{"crew"} )$$ $$P(\text{sex} = \text{"Male"}, \text{class} = \text{"crew"} | \text{survived} = \text{"Yes"} )$$

Thanks for your help.

here is the R code:


# built in R data

# convert to a tibble
titanic_tbl <- as.tibble(Titanic)

# replicate the rows using the library "splitstackshape" - from count to rows
titanic_tbl_r <- expandRows(titanic_tbl, "n")
str(titanic_tbl_r) #the variable n is removed

# create freq tables 

class_f <- addmargins(table(titanic_tbl_r$Class))
# sex
sex_f <- addmargins(table(titanic_tbl_r$Sex))
# age
age_f <- addmargins(table(titanic_tbl_r$Age))
# survived
surv_f <- addmargins(table(titanic_tbl_r$Survived))

# contingency tables
# classXsex
classSex_c <- addmargins(table(titanic_tbl_r$Class, titanic_tbl_r$Sex))

# class X survived
classSurv_c <- addmargins(table(titanic_tbl_r$Class, titanic_tbl_r$Survived))

# sex X survived
SexSurv_c <- addmargins(table(titanic_tbl_r$Sex, titanic_tbl_r$Survived))

# p1 :  prb(Sex = "Male" | class = "crew")

p1 <- classSex_c[4,2]/classSex_c[4,3]
p1 <- p1*100

# P2: prob(sex = "Male", class = "crew"  | survived = "Yes" )

# p3: prob (survived = "Yes" | sex = "Male", class = "crew" )


For example, you could find P(survived | male, crew) by dividing number of data points that are male, crew (i.e. the denominator) by number of data points that are male and crew and survived (i.e. the numerator). This isn't Bayes explicitly, since we're not dividing up probabilities, rather number of points inside our events. You've already done this in calculating P(male | crew).

Similarly, for P(male, crew | survived), you'll divide the number of data points that survived the accident by the number of data points that are male, crew as well as survived the accident.

We're employing the following rules, which is safe to use when the sets are finite:

$$P(A|B\cap C)=\frac{s(A\cap B\cap C)}{s(B\cap C)}, \ \ P(B\cap C|A)=\frac{s(A\cap B\cap C)}{s(A)}$$

  • 1
    $\begingroup$ Thank you very much. Following your formula, I found that: P2: prob(sex = "Male", class = "crew" | survived = "Yes" ) = P2 = 192/711=.27 and p3=prob (survived = "Yes" | sex = "Male", class = "crew" ) = P3 = 192/862 = .22 $\endgroup$ – Wolfpack_1 Aug 30 at 19:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.