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

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

+7
r
source share
2 answers

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.

+10
source share

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

+2
source share

All Articles