2016-01-03 39 views
2

我想對某些時間序列數據應用分析權重,但不知道如何在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 
+1

入門摘要:http://www.cookbook-r.com/Manipulating_data/Summarizing_data/ – patrickmdnet

+1

你能清楚地說明了目的? 「collapse」的默認func是「mean」;你是否想要按農作物分類加權的臨時分類的平均值,按年分組? – patrickmdnet

+0

@patrickmdnet是的,這是我以後,但每個ID。我想我需要一個更大的數據集。 – Vedda

回答

2

感謝包括樣本數據!這使事情變得更容易。

Stata collapse類似於R functions aggregate or ddply。它看起來像你想加權(croparea)的平均值temp分組id

For weighted means in R see this SO question;我要頂的解決方案,並將其應用到你的數據:這裏的食譜

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 
+0

謝謝。這看起來不錯。 r中是否有其他函數用於加權?我不知道加權平均值 – Vedda

+0

是否可以使用'dplyr'來代替?不知道如何實現這一點 – Vedda