I've created a function to compute Bayes's theorem from a vector probabilidades
that includes all the probabilities involved (in the proper order, though this is only key to the numerator in the formula):
bayes = function(probabilidades)
{
numerador = probabilidades[1] * probabilidades[2]
producto = c() #Inicio del cálculo de la probabilidad total
sumandos = c()
for(probabilidad in probabilidades)
{
producto = c(producto, probabilidad)
if(length(producto) == 2)
{
sumando = prod(producto)
sumandos = c(sumandos, sumando)
producto = c()
}
}
denominador = sum(sumandos) #Fin del cálculo de la probabilidad total
return(numerador/denominador)
}
The whole computation part of the total probability theorem (the denominator of the Bayes formula) seems like a pretty hard tripe to me, and I was wondering if there was a way to make the code more elegant, possibly with a function sapply()
.
It would be a matter of multiplying the elements of the vector two by two and returning the sum of all these products, regardless of the number (which, yes, must be even) of probabilities: p1 * p2 + p3 * p4 + p5 * p6
, etc.