2014-10-03 41 views
1

我正在處理由多個問題(y1,y2,y3,...)的整數值響應和分配給每個應答者的加權計數組成的調查數據,如下所示:加權表格數據框與plyr

foo <- data.frame(wcount = c(10, 1, 2, 3),  # weighted counts 
        y1 = sample(1:5, 4, replace=T), # numeric responses 
        y2 = sample(1:5, 4, replace=T), # 
        y3 = sample(1:5, 4, replace=T)) # 
>foo 
    wcount y1 y2 y3 
1  10 5 5 5 
2  1 1 4 4 
3  2 1 2 5 
4  3 2 5 3 

我想將其轉換爲加權表的統一數據框版本,第一列代表響應值,接下來的3列代表加權計數。

library(Hmisc) 
ty1 <- wtd.table(foo$y1, foo$wcount) 
ty2 <- wtd.table(foo$y2, foo$wcount) 
ty3 <- wtd.table(foo$y3, foo$wcount) 

bar <- merge(ty1, ty2, all=T, by="x") 
bar <- merge(bar, ty3, all=T, by="x") 

names(bar) <- c("x", "ty1", "ty2", "ty3") 
bar[is.na(bar)]<-0 
>bar 
    x ty1 ty2 ty3 
1 1 3 0 0 
2 2 3 2 0 
3 3 0 0 3 
4 4 0 1 1 
5 5 10 13 12 

我懷疑有與plyr和numcolwise或ddply這種自動化的方法:可以明確地列使用來完成。例如,以下內容即將結束,但我不確定還需要完成該任務:

library(plyr) 
bar2 <- numcolwise(wtd.table)(foo[c("y1","y2","y3")], foo$wcount) 
>bar2 
     y1  y2  y3 
1 1, 2, 5 2, 4, 5 3, 4, 5 
2 3, 3, 10 2, 1, 13 3, 1, 12 

有什麼想法?

+0

嗨,你正在使用什麼調查?這看起來像多重填補,需要'mitools' +'survey'包來獲得正確的置信區間。 – 2014-10-03 21:12:23

+0

我正在與環境影響評估等美國住宅能源消費調查(RECS)合作。很高興看到有一個關於一切的包,謝謝參考! – Bryan 2014-10-04 00:38:42

+0

這只是一個基於複製的調查。你試圖重新發明輪子......你將有一個更容易的時間[複製他們的官方方法](http://www.eia.gov/consumption/residential/methodology/2009/pdf/using-microdata- 022613.pdf)如果您使用調查軟件包。 :) – 2014-10-04 04:17:41

回答

1

不是plyr的答案,但是這給我的印象重塑/聚合,可以直截了當地用從包reshape2功能來解決問題。

首先,melt數據集,使響應值的一列可以命名爲xy1 - y3中的唯一值)。

library(reshape2) 
dat2 = melt(foo, id.var = "wcount", value.name = "x") 

現在,這可以與廣投dcast回,使用sum作爲聚合功能。這將y1 - y3作爲列,總計爲wcount,每個值爲x

# Cast back wide using the values within y1-y3 as response values 
    # and filling with the sum of "wcount" 
dcast(dat2, x ~ variable, value.var = "wcount", fun = sum) 

給予

x y1 y2 y3 
1 1 3 0 0 
2 2 3 2 0 
3 3 0 0 3 
4 4 0 1 1 
5 5 10 13 12 
+0

這很好,謝謝!我一直在使用融化,但我是一個演員新手,所以這是非常有幫助的。出於學習目的,我仍然有興趣瞭解是否/如何使用ddply完成這項工作,如果沒有,爲什麼不呢。 – Bryan 2014-10-03 20:21:55

0

你所描述的是使用重複權的一項調查數據集。看到http://asdfree.com/許多很多的例子,但對於recs,做這樣的事情:

library(survey) 

x <- read.csv("http://www.eia.gov/consumption/residential/data/2009/csv/recs2009_public.csv") 
rw <- read.csv("http://www.eia.gov/consumption/residential/data/2009/csv/recs2009_public_repweights.csv") 
y <- merge(x , rw) 

# create a replicate-weighted survey design object 
z <- svrepdesign(data = y , weights = ~NWEIGHT , repweights = "brr_weight_[0-9]") 

# now run all of your analyses on the object `z` .. 
# see the `survey` package homepage for details 

# distribution 
svymean(~ factor(BASEHEAT) , z) 

# mean 
svymean(~ TOTHSQFT , z) 
+0

謝謝你的例子! FWIW,我的最終目標不是找到具有CI的彙總統計數據,而是使用加權直方圖和加權經驗cdf圖格式來探索幾個連續響應(例如溫度設置)的分佈,該圖不支持權重(除了密度圖),所以我不得不重新格式化數據以顯示我想要的內容。調查提供了這些功能中的一部分,但我更喜歡多格調節功能來繪製格子。將需要花一些時間玩調查,看看他們是否可以一起工作。 – Bryan 2014-10-04 13:59:03