tags:

views:

108

answers:

2

Given a random variable with probability density function f(x), how to compute the expected value of this random variable in R?

+1  A: 

Does it help to know that the expectation E is the integral of x*f(x) dx for x in (-inf, inf)?

Jim Lewis
+7  A: 

If you want to compute the expected value, just compute :

E(X) = Integral of xf(x)dx over the whole domain of X.

The integration can easily be done using the function integrate().

Say you're having 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 by:

f2 <- function(x){x*f(x)}
integrate(f2,-Inf,Inf )

Pay attention, sometimes you need to use Vectorize() for your function. This is necessary to get integrate to work. For more info, see the help pages of integrate() and Vectorize().

Joris Meys
Why `Vectorize` is needed? `f2` is already vectorized function. Or I missed something?
Marek
In this case, it is. I just wanted to point out the obvious error when using integrate. I've seen it many times before. I'll correct
Joris Meys