如何在R中计算加权平均数?
加权平均数是指通过计算权重和值的乘积之和,然后将此和除以权重总和来确定的平均数。如果权重成比例,则权重总和应为1。在R语言中,我们有一个`weighted.mean`函数可以计算加权平均数,我们只需要传入值向量和权重向量即可。
示例
x1<-c(1,2,3,4) x1
输出
[1] 1 2 3 4
示例
Weight_x1<-c(0.25,0.25,0.25,0.25) Weight_x1
输出
[1] 0.25 0.25 0.25 0.25
示例
Weighted_Mean_x1<-weighted.mean(x1,Weight_x1) Weighted_Mean_x1
输出
[1] 2.5
示例
x2<-rpois(10,5) x2
输出
[1] 3 3 4 6 6 10 5 3 3 6
示例
Weight_x2<-rep(0.1,10) Weight_x2
输出
[1] 0.1 0.1 0.1 0.1 0.1 0.1 0.1 0.1 0.1 0.1
示例
Weighted_Mean_x2<-weighted.mean(x2,Weight_x2) Weighted_Mean_x2
输出
[1] 4.9
示例
x3<-c(8,6,7) x3
输出
[1] 8 6 7
示例
Weight_x3<-c(0.5,0.3,0.2) Weight_x3
输出
[1] 0.5 0.3 0.2
示例
Weighted_Mean_x3<-weighted.mean(x3,Weight_x3) Weighted_Mean_x3
输出
[1] 7.2
示例
x4<-rnorm(5,1.5) x4
输出
[1] 3.0320687 0.9741989 0.2783473 0.8061909 0.5833953
示例
Weight_x4<-rep(0.2,5) Weight_x4
输出
[1] 0.2 0.2 0.2 0.2 0.2
示例
Weighted_Mean_x4<-weighted.mean(x4,Weight_x4) Weighted_Mean_x4
输出
[1] 1.13484
示例
x5<-c(1,2,5,7) x5
输出
[1] 1 2 5 7
示例
Weight_x5<-c(2,14,8,32) Weight_x5
输出
[1] 2 14 8 32
示例
Weighted_Mean_x5<-weighted.mean(x5,Weight_x5) Weighted_Mean_x5
输出
[1] 5.25
示例
x6<-runif(10,2,4) x6
输出
[1] 2.126860 3.194281 3.051176 3.083388 3.393485 2.139493 2.634237 2.647985 [9] 3.318430 2.765557
示例
Weight_x6<-rep(0.1,10) Weight_x6
输出
[1] 0.1 0.1 0.1 0.1 0.1 0.1 0.1 0.1 0.1 0.1
示例
Weighted_Mean_x6<-weighted.mean(x6,Weight_x6) Weighted_Mean_x6
输出
[1] 2.835489
示例
x7<-c(1,2,3,4) x7
输出
[1] 1 2 3 4
示例
Weight_x7<-c(73,378,459,90) Weight_x7
输出
[1] 73 378 459 90
示例
Weighted_Mean_x7 <-weighted.mean(x7,Weight_x7) Weighted_Mean_x7
输出
[1] 2.566
广告