How to Calculate Expected Value in R?

Last Updated : 29 Jul, 2025

To calculate the expected value in R, we use the formula for the expected value of a probability distribution. This value represents the average or mean of all possible outcomes, weighted by their probabilities.

Expected Value Formula

\mu = \sum (x \times P(x))

  • x: sample value
  • P(x): probability of the sample value

Example

Given:

X: 0.2, 0.3, 0.4, 0.5, 0.6

P(x): .1, .3, .5, .1, .2

\mu = (0.2 \times 0.1) + (0.3 \times 0.3) + (0.4 \times 0.5) + (0.5 \times 0.1) + (0.6 \times 0.2) = 0.48

Method 1: Using sum() method

sum() method is used to calculate the sum of given vector

Syntax:

sum(x)

Parameters:

  • x: Numeric Vector

Example: Calculate expected value

R
x <- c(0.2, 0.3, 0.4, 0.5, 0.6)
probability <- c(0.1, 0.3, 0.5, 0.1, 0.2)
sum(x * probability)

Output:

0.48

Method 2: Using weighted.mean() method

It is used to get the weighted arithmetic mean of input vector values.

Syntax:

weighted.mean(x, weights)

Parameters:

  • x: data input vector
  • weights: weights for the input data
  • Returns: weighted mean of the values

Example: Calculate expected value

R
x <- c(0.2, 0.3, 0.4, 0.5, 0.6)
probability <- c(0.1, 0.3, 0.5, 0.1, 0.2)
weighted.mean(x, probability)

Output:

0.4

Method 3: Using c() method

It is used to combine the arguments passed to it. And %% operator is used to multiply a matrix with its transpose.

Syntax:

c(…)

Parameters:

  • …: arguments to be combined

Example: Calculate expected value

R
x <- c(0.2, 0.3, 0.4, 0.5, 0.6)
probability <- c(0.1, 0.3, 0.5, 0.1, 0.2)
c(x %*% probability)

Output:

0.48

Matrix multiplication returns the expected value 0.48.

Comment

Explore