Open In App

Calculate the Weighted Mean in R Programming – weighted.mean() Function

Improve
Improve
Like Article
Like
Save
Share
Report

weighted.mean() function in R Language is used to compute 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 1:




# Create example data
x1 <- c(1, 2, 7, 5, 3, 2, 5, 4)
  
# Create example weights                    
w1 <- c(7, 5, 3, 5, 7, 1, 3, 7)                    
  
# Apply weighted.mean() function
weighted.mean(x1, w1)


Output:

[1] 3.394737

Example 2:




# Create example data
x1 <- c(1, 2, 7, 5, 3, 2, 5, 4)
  
# Create example weights                    
w1 <- c(7, 5, 3, 8, 7, 1, 3, 7)                    
  
# Create vector with NA
# Extend weights vector
x2 <- c(x1, NA)                                    
w2 <- c(w1, 3)                                     
weighted.mean(x2, w2)      
  
# Remove missing values
weighted.mean(x2, w2, na.rm = TRUE)  


Output:

[1] NA
[1] 3.512195

Last Updated : 23 Jun, 2020
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads