How to calculate the variance and expected value of a random variable with density function f(x) in R was wondering how to calculate the expected value and variance of some function f(x).
For the Expected value $\mu,$ I integrated x*f(x) and I'm confident that is correct, but I'm confused about how to calculate the variance using integrals and f(x).
I was wondering if I should use: This Formula for Variance
$Var(X) = E(X^2) - \mu^2.$
where I would set a variable to the value of the expected value I found earlier and use that formula.
Any help would be greatly appreciated.
 A: Example: If $X \sim \mathsf{Beta}(2,1)$, which has density function $f_X(x) = 2x,$ for $0 < x < 1$ and $0$ elsewhere. [See Wikipedia on beta distributions.]
Then
$$\mu_X = E(X) = \int_0^1 xf_X(x)\,dx = \int_0^1 x(2x)\,dx\\
=\int_0^1 2x^2\,dx = 2/3.$$
Also,
$$\sigma_X^2=Var(X) = E(X^2) - \mu_X^2 = \int_0^1 x^2f_X(x)\,dx - (2/3)^2\\ = \int_0^1 2x^3\, dx - (2/3)^2
=1/2 - (2/3)^2 = 1/18.$$
Maybe you can practice with the first formula for $Var(X).$
Approximation by simulation in R for reality check (to a couple of decimal places of accuracy):
set.seed(2020)  # for reproducibility
x = rbeta(10^6, 2, 1)
mean(x)
[1] 0.6665343   # aprx E(X) = 2/3
var(x)
[1] 0.05551495  # aprx Var(X) = 1/18
1/18
[1] 0.05555556

Note: There is a numerical integration procedure in R, where dbeta is the PDF
of a beta distribution. Here is a rudimentary introduction for
finding $E(X) = 2/3$ and $E(X^2)=1/2.$
integrand1 = function(x){x*dbeta(x,2,1)}
integrate(integrand1, 0, 1)
0.6666667 with absolute error < 7.4e-15

integrand2 = function(x)(x^2*dbeta(x,2,1))
integrate(integrand2,0,1)
0.5 with absolute error < 5.6e-15

