How to Calculate Expected Value in R?
Last Updated :
12 Jan, 2022
In this article, we are going to see how to calculate the excepted value using R Programming Language. A probability distribution describes all the possible values of random variables in the given range.
Expected value of a probability distribution:
Where X is a Sample value and P(x) is a Probability of a simple value
Example:
X: 0.2, 0.3, 0.4, 0.5, 0.6
P(x): .1, .3, .5, .1, .2
μ = (0.2*0.1) + (0.3*0.3) + (0.4 * 0.5) + (0.5*0.1) + (0.6*0.2) = 0.48
Explanation: The expected value of probability distribution calculated with Σx * P(x) formula
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 (.1, .3, .5, .1, .2)
sum (x*probability)
|
Output:
0.48
It is used to get the weighted arithmetic mean of input vector values.
Syntax: weighted.mean(x, weights)
Parameters:
- x: data input vector
- weights: It is weight of input data.
- Returns: weighted mean of given values
Example: Calculate expected value
R
x <- c (0.2, 0.3, 0.4, 0.5, 0.6)
probability <- c (.1, .3, .5, .1, .2)
weighted.mean (x, probability)
|
Output:
0.48
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 (.1, .3, .5, .1, .2)
c (x %*% probability)
|
Output:
0.48
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...