Home Â» How to Calculate Expected Value in R (With Examples)

# How to Calculate Expected Value in R (With Examples)

A probability distribution tells us the probability that a random variable takes on certain values.

For example, the following probability distribution tells us the probability that a certain soccer team scores a certain number of goals in a given game:

To find the expected value of a probability distribution, we can use the following formula:

Î¼ = Î£x * P(x)

where:

• x: Data value
• P(x): Probability of value

For example, the expected number of goals for the soccer team would be calculated as:

Î¼ = 0*0.18Â  +Â  1*0.34Â  +Â  2*0.35Â  +Â  3*0.11Â  +Â  4*0.02Â  =Â Â 1.45 goals.

To calculate expected value of a probability distribution in R, we can use one of the following three methods:

```#method 1
sum(vals*probs)

#method 2
weighted.mean(vals, probs)

#method 3
c(vals %*% probs)
```

All three methods will return the same result.

The following examples show how to use each of these methods in R.

### Example 1: Expected Value Using sum()

The following code shows how to calculate the expected value of a probability distribution using the sum() function:

```#define values
vals
#define probabilities
probs
#calculate expected value
sum(vals*probs)

[1] 1.45
```

### Example 2: Expected Value Using weighted.mean()

The following code shows how to calculate the expected value of a probability distribution using the built-in weighted.mean() function in R:

```#define values
vals
#define probabilities
probs
#calculate expected value
weighted.mean(vals, probs)

[1] 1.45```

### Example 3: Expected Value Using c()

The following code shows how to calculate the expected value of a probability distribution using the built-in c() function in R:

```#define values
vals
#define probabilities
probs
#calculate expected value
c(vals %*% probs)

[1] 1.45```

Notice that all three methods returned the same expected value.