If you want to calculate the expected value, just calculate:
E (X) = The integral xf (x) dx over the entire domain X.
Integration can be easily done using the integrate () function.
Say you have a normal density function (you can easily define your own density function):
f <- function(x){ 1/sqrt(2*pi)*exp((-1/2)*x^2) }
You calculate the expected value simply:
f2 <- function(x){x*f(x)} integrate(f2,-Inf,Inf )
Note that sometimes you need to use Vectorize () for your function. This is necessary for integration into the work. See the Help Pages with Integration () and Vectorize () for more information.
Joris meys
source share