Calculate the Weighted Mean in R
Calculate the Weighted Mean in R, In this lesson for the R programming language, we’ll go over how to compute the weighted mean.
The weighted.mean() function serves as the foundation for the tutorial. So let’s first look at the definition of the weighted.mean function and the fundamental R syntax:
Calculate the Weighted Mean in R
weighted.mean(x, weights)
The weighted arithmetic mean of a numeric input vector is calculated by the weighted.mean function.
Five examples, of reproducible R programs, are provided in this article. You came here looking for the solution, so let’s get to the examples now!
Example 1: Weighted.mean Function in R Basic Application
We must first construct some sample data as well as a vector and weights for it. Take into account the following sample data:
x1 <- c(19, 15, 12, 71, 13, 26, 34, 15) w1 <- c(2, 3, 1, 5, 7, 1, 3, 7)
We can now compute the weighted mean of these data using the weighted.mean command:
weighted.mean(x1, w1) [1] 26.68966
The RStudio console output shows that the weighted mean of our data is, as you can see 26.68966.
Example 2: Using the weighted.mean Function to handle NAs
The presence of missing values in our data, often known as NA values, is a common issue. Let us add NA values to our example data to model this scenario:
x2 <- c(x1, NA) w2 <- c(w1, 3)
The RStudio console returns NA if we now use the weighted.mean function as in Example 1:
weighted.mean(x2, w2) NA
Fortunately, the weighted.mean function’s na.rm option makes it simple to ignore NA values in our data:
weighted.mean(x2, w2, na.rm = TRUE) [1] 26.68966
Example 3: Calculate Weighted Means by Group
Frequently, we are only concerned with learning the weighted mean for a particular subset of our data. Take into account the following sample data:
group <- c("A", "B", "A", "C", "C", "A", "B", "B") data <- data.frame(x1, w1, group)
We can use the dplyr package’s functions to compute the weighted mean by group. Installing and loading the package into R now
install.packages("dplyr") library("dplyr")
data %>% group_by(group) %>% summarise(weighted.mean(x1, w1))
or
install.packages("matrixStats") library("matrixStats") weightedMean(x1, w1)
or
install.packages("SDMTools") library("SDMTools") wt.mean(x1, w1)