我想对一些时间序列数据应用分析权重,但不确定如何在R中做到这一点。我正在转录一些Stata
代码,该代码使用collapse
和[aweight='weightVar']
。
Stata代码
collapse temp [aweight='weightVar], by(year);
如何将分析权重应用于数据?使用下面的croparea
作为每年每个id的temp
的权重变量?
样本数据
df <- structure(list(id = c(1, 1, 1, 1, 2, 2, 2, 2), year = c(1900,
1900, 1900, 1900, 1901, 1901, 1901, 1901), month = c(1L, 2L,
3L, 4L, 1L, 2L, 3L, 4L), temp = c(51.8928991815029, 52.8768994596968,
70.0998976356871, 62.2724802472936, 51.8928991815029, 52.8768994596968,
70.0998976356871, 62.2724802472936), croparea = c(50, 50, 50,
50, 30, 30, 30, 30)), .Names = c("id", "year", "month", "temp",
"croparea"), row.names = c(NA, -8L), class = "data.frame")
id year month temp croparea
1 1 1900 1 51.89290 50
2 1 1900 2 52.87690 50
3 1 1900 3 70.09990 50
4 1 1900 4 62.27248 50
5 2 1901 1 51.89290 30
6 2 1901 2 52.87690 30
7 2 1901 3 70.09990 30
8 2 1901 4 62.27248 30
感谢您提供示例数据!这让事情变得容易多了。
Stata collapse
类似于R函数aggregate
或ddply
。看起来您想要temp
的加权(由croparea
)平均值由id
分组。
关于R中的加权平均数,请参见SO问题;我将采用顶级解决方案并将其应用于您的数据:
library(plyr)
ddply(df, .(id), function(x) data.frame(wtempmean=weighted.mean(x$temp, x$croparea)))
id wtempmean
1 1 59.28554
2 2 59.28554