1

Suppose values of a discrete random variable X, randomNumbers, and its distribution prob is given.

I can find E(X) using the following code:

weighted.mean(randomNumbers, prob)

How can we find E(X^n) in R?

Would this code work?

weighted.mean(randomNumbers^n, prob)
divibisan
  • 11,659
  • 11
  • 40
  • 58
user366312
  • 16,949
  • 65
  • 235
  • 452

1 Answers1

3

Take Poisson random variable X ~ Poisson(2) for example.

probabilistic method

f1 <- function (N) {
  x <- 0:N
  p <- dpois(x, 2)
  ## approximate E[X]
  m1 <- weighted.mean(x, p)
  ## approximate E[X ^ 2]
  m2 <- weighted.mean(x ^ 2, p)
  ## approximate E[X ^ 3]
  m3 <- weighted.mean(x ^ 3, p)
  ## return
  c(m1, m2, m3)
  }

As N gets bigger, approximation is more and more accurate, in the sense that the sequence converges analytically.

N <- seq(10, 200, 10)
m123_prob <- t(sapply(N, f1))
matplot(m123_prob, type = "l", lty = 1)

statistical method (sampling based method)

f2 <- function (sample_size) {
  x <- rpois(sample_size, 2)
  ## unbiased estimate of E[x]
  m1 <- mean(x)
  ## unbiased estimate of E[x ^ 2]
  m2 <- mean(x ^ 2)
  ## unbiased estimate of E[x ^ 3]
  m3 <- mean(x ^ 3)
  ## return
  c(m1, m2, m3)
  }

As sample_size grows, estimation is more and more accurate, in the sense that the sequence converges in probability.

sample_size <- seq(10, 200, 10)
m123_stat <- t(sapply(sample_size, f2))
matplot(m123_stat, type = "l", lty = 1)
Zheyuan Li
  • 71,365
  • 17
  • 180
  • 248