gpt4 book ai didi

R加权算术平均数

转载 作者:行者123 更新时间:2023-12-03 19:55:49 25 4
gpt4 key购买 nike

假设我在 R 中有这个 data.frame:

ages <- data.frame(Indiv = numeric(),
Age = numeric(),
W = numeric())
ages[1,] <- c(1,10,2)
ages[2,] <- c(1,15,5)
ages[3,] <- c(2,5,1)
ages[4,] <- c(2,100,2)

ages

Indiv Age W
1 1 10 2
2 1 15 5
3 2 5 1
4 2 100 2

如果我这样做:

meanAge <- aggregate(ages$Age,list(ages$Indiv),mean)

我得到每个 Indiv (Group.1) 的平均年龄 (x):

  Group.1    x
1 1 12.5
2 2 52.5

但是我想计算年龄的加权算术平均值(权重为W)。如果我这样做:

WmeanAge <- aggregate(ages$Age,list(ages$Indiv),weighted.mean,ages$W)

我得到:

Error in weighted.mean.default(X[[1L]], ...) : 
'x' and 'w' must have the same length

我认为我应该:

  Group.1           x
1 1 13.57142857
2 2 68.33333333

我做错了什么?提前致谢!

最佳答案

Doh,你比我还早。但无论如何,这是我同时使用 plyrdplyr 的答案:

ages = data.frame(Indiv = c(1,1,2,2),
Age = c(10,15,5,100),
W = c(2,5,1,2))

library(plyr)
ddply(ages, .(Indiv), summarize,
mean = mean(Age),
wmean = weighted.mean(Age, w=W))


library(dplyr)
ages %.%
group_by(Indiv) %.%
summarise(mean = mean(Age), wmean = weighted.mean(Age, W))

关于R加权算术平均数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23502697/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com