Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

r

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

like image 686
user297850 Avatar asked Sep 07 '10 04:09

user297850


People also ask

How do you find the expected value of x in a probability density function?

To find the expected value, E(X), or mean μ of a discrete random variable X, simply multiply each value of the random variable by its probability and add the products. The formula is given as E(X)=μ=∑xP(x).

How do you calculate expected variability?

For any random variable X , the variance of X is the expected value of the squared difference between X and its expected value: Var[X] = E[(X-E[X])2] = E[X2] - (E[X])2 .


2 Answers

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().

like image 63
Joris Meys Avatar answered Sep 23 '22 01:09

Joris Meys


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

like image 23
Jim Lewis Avatar answered Sep 19 '22 01:09

Jim Lewis