Search code examples
rmeandistributionintegralcontinuous

How to calculate mean (Expected Value) of a custom continuous distribution from the probability density in R


The probability density and the calculation for the mean "by hand" are given below: enter image description here

I have coded the probability density function as:

myfunc <- function(x){
  ifelse(x >= 0 & x < 0.5, 1,
         ifelse (x >= 0.5 & x < 1, 0.2,
                 ifelse(x >= 1 & x < 2, 0.8*(x-1), 0)))
}

I understand that the EV is the weighted integral but I am struggling to code the calculation.

Also, additionally: how could I simulate this (0.867) result over the long run?

Could someone help, please?


Solution

  • Here is one solution with integrate:

    integrate(function(x) x*myfunc(x),lower=0,upper=2)
    
    0.866666666666667 with absolute error < 9.6e-15