6

I'm sure there must be a straight forward command for this, but I've searched and can't find one. How do I get the expected value from a vector?

Here are the values

y <- c(0.05, 0.01, -0.1)

And their probabilities

p <- c(0.2, 0.7, 0.1)

I can get E(Y) by doing

sum(y*p)

But I think there is probably a command for it right, I just can't find it. Thanks!

Andrie
  • 176,377
  • 47
  • 447
  • 496
Tim H UK
  • 285
  • 1
  • 3
  • 10
  • 3
    Nope. That's is. When it's that easy, why implement a special command for it? – MrFlick Nov 16 '14 at 16:22
  • @MrFlick But think of the possibilities! Feed `y` and `p` into a spline calculator, generate the distribution function, and *then* calculate the expected value by applying calculus to said function! – Carl Witthoft Nov 16 '14 at 16:25

2 Answers2

15

You can use weighted.mean:

weighted.mean(y, p)
# [1] 0.007
Sven Hohenstein
  • 80,497
  • 17
  • 145
  • 168
  • Thanks this was great. This lead me to find Hmisc and SDMTools, unfortunately neither of their weighted variances worked as expected. Hmisc's wtd.var(y, weights=p, normwt=TRUE) returned 0.0022815 while SDMTools' wt.var(y, p) returned 0.003306522 What I'd like to find now though is a command that returns this weighted.mean(y^2, p)-weighted.mean(y, p)^2 If anyone knows of a library let me know, thanks! – Tim H UK Nov 16 '14 at 18:14
  • Did you mean var(y) ? @TimHUK – eja08 Dec 17 '19 at 22:11
5

Here's another option:

> c(y %*% p)
[1] 0.007
nrussell
  • 18,382
  • 4
  • 47
  • 60