R语言 计算加权平均数 – weighted.mean() 函数
R语言中的 weighted.mean() 函数用于计算输入向量值的加权算术平均值。
语法: weighted.mean(x, weights)
参数:
x: 数据输入向量
weights: 它是输入数据的权重。
返回: 给定数值的加权平均数
例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