# How to calculate weighted mean in R?

R ProgrammingServer Side ProgrammingProgramming

Weighted mean is the average which is determined by finding the sum of the products of weights and the values then dividing this sum by the sum of total weights. If the weights are in proportion then the total sum of the weights should be 1. In base R, we have a function weighted.mean to find the weighted mean in which we just need to pass the vector of values and the vector of weights.

## Examples

Live Demo

x1<-c(1,2,3,4)
x1

## Output

[1] 1 2 3 4

## Example

Live Demo

Weight_x1<-c(0.25,0.25,0.25,0.25)
Weight_x1

## Output

[1] 0.25 0.25 0.25 0.25

## Example

Weighted_Mean_x1<-weighted.mean(x1,Weight_x1)
Weighted_Mean_x1

## Output

[1] 2.5

## Example

Live Demo

x2<-rpois(10,5)
x2

## Output

[1] 3 3 4 6 6 10 5 3 3 6

## Example

Live Demo

Weight_x2<-rep(0.1,10)
Weight_x2

## Output

[1] 0.1 0.1 0.1 0.1 0.1 0.1 0.1 0.1 0.1 0.1

## Example

Weighted_Mean_x2<-weighted.mean(x2,Weight_x2)
Weighted_Mean_x2

## Output

[1] 4.9

## Example

Live Demo

x3<-c(8,6,7)
x3

## Output

[1] 8 6 7

## Example

Live Demo

Weight_x3<-c(0.5,0.3,0.2)
Weight_x3

## Output

[1] 0.5 0.3 0.2

## Example

Weighted_Mean_x3<-weighted.mean(x3,Weight_x3)
Weighted_Mean_x3

## Output

[1] 7.2

## Example

Live Demo

x4<-rnorm(5,1.5)
x4

## Output

[1] 3.0320687 0.9741989 0.2783473 0.8061909 0.5833953

## Example

Live Demo

Weight_x4<-rep(0.2,5)
Weight_x4

## Output

[1] 0.2 0.2 0.2 0.2 0.2

## Example

Weighted_Mean_x4<-weighted.mean(x4,Weight_x4)
Weighted_Mean_x4

## Output

[1] 1.13484

## Example

Live Demo

x5<-c(1,2,5,7)
x5

## Output

[1] 1 2 5 7

## Example

Weight_x5<-c(2,14,8,32)
Weight_x5

## Output

[1] 2 14 8 32

## Example

Weighted_Mean_x5<-weighted.mean(x5,Weight_x5)
Weighted_Mean_x5

## Output

[1] 5.25

## Example

Live Demo

x6<-runif(10,2,4)
x6

## Output

[1] 2.126860 3.194281 3.051176 3.083388 3.393485 2.139493 2.634237 2.647985
[9] 3.318430 2.765557

## Example

Weight_x6<-rep(0.1,10)
Weight_x6

## Output

[1] 0.1 0.1 0.1 0.1 0.1 0.1 0.1 0.1 0.1 0.1

## Example

Weighted_Mean_x6<-weighted.mean(x6,Weight_x6)
Weighted_Mean_x6

## Output

[1] 2.835489

## Example

Live Demo

x7<-c(1,2,3,4)
x7

## Output

[1] 1 2 3 4

## Example

Weight_x7<-c(73,378,459,90)
Weight_x7

## Output

[1] 73 378 459 90

## Example

Weighted_Mean_x7
<-weighted.mean(x7,Weight_x7)
Weighted_Mean_x7

## Output

[1] 2.566
Published on 08-Sep-2020 11:36:19