我想将分析权重应用于一些时间序列数据,但是不确定如何在R中执行此操作。我正在转录一些Stata
代码,并且代码使用collapse
和[aweight='weightVar']
。
州代码
collapse temp [aweight='weightVar], by(year);
如何将分析权重应用于croparea
以下数据,作为temp
每年每个ID的权重变量?
样本数据
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
感谢您提供示例数据!这使事情变得容易得多。
Statacollapse
与R函数aggregate
或ddply
相似。它看起来像你想有一个加权(按croparea
)的意思是temp
按分组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
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句