Probabilities in R (Bayes Rule example)

This code shows an example that implements Bayes Rule. In this case it calculates a posteriori probabilities for a case of a components based system failure. (code is documented)


#Probability

#Bayes Rule
#Problem2:
# C1:"Components of type 1 in a system",
# C2="Components of type 2 in a system", 
# C3="Components of type 3 in a system"
# F ="A component of the system fails"
# F given C1 = "System fails because a component of type 1"
# F given C2 = "System fails because a component of type 2"
# F given C3 = "System fails because a component of type 3"

# We want to know (posteriori): If system fails what are: P(C1| F) , P(C2|F), P(C3|F)

# Priori probs 
pC1 <- 40/100
pC2 <- 45/100
pC3 <- 15/100
prioris <- c(pC1,pC2,pC3)

# Prob of system failure
pF <- 0 # we will calculate this later, for that we will use Total probability theorem

#Likelihoods
pFgC1 <- 2/1000 #C1 avg prob of fail is 2 over 1000 components
pFgC2 <- 0.5/1000
pFgC3 <- 4/1000

likelihoods <- c(pFgC1,pFgC2,pFgC3)
#
# P(C1 and F), P(C2 and F), P(C3 and F) : remind* Bayes-> P(A given B) = P(A and B) / P(B)
intersections <- prioris * likelihoods
#Total probability gives us P(F)
pF <- sum(intersections)
#Bayes theorem
posterioris <- intersections/pC

# P(C1| F) , P(C2|F), P(C3|F)
posterioris


cat("Probability that system fails:", pF, " Percentage:" , pF*100, "\n")

for(i in 1:length(posterioris)){
  cat("Failure because  component of Type " , i , " =  ", posterioris[i], " Percentage: " , posterioris[i] *100,"\n")
}



Comments

Popular posts from this blog

3D with POV-Ray, isosurfaces example

Algorithms: Backpack problem, Greedy , Dynamic Programming techniques (C++)

Classic Email, Web mail application refactory for visual effects (software engineering-efficiency-UX)