计算 R 编程中的加权平均值 – weighted.mean()函数
R 语言中的weighted.mean()
函数用于计算输入向量值的加权算术平均值。
Syntax: weighted.mean(x, weights)
Parameters:
x: data input vector
weights: It is weight of input data.
Returns: weighted mean of given values
示例 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)
输出:
[1] 3.394737
示例 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)
输出:
[1] NA
[1] 3.512195