# Discrete Conditional probability and Bayes Rule

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.

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"} )$$

here is the R code:

library(tidyverse)
library(splitstackshape)

# built in R data
Titanic

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

# 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
class_f <- addmargins(table(titanic_tbl_r$$Class)) class_f # sex sex_f <- addmargins(table(titanic_tbl_r$$Sex))
sex_f
# age
age_f <- addmargins(table(titanic_tbl_r$$Age)) age_f # survived surv_f <- addmargins(table(titanic_tbl_r$$Survived))
surv_f

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

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

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

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

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

# 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)}$$

• 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 – Wolfpack_1 Aug 30 at 19:33