如何汇总加权数据

时间:2015-06-12 14:33:19

标签: r dplyr summary

是否有可能使用dplyr的权重:

summarise 

功能

让我们想象一下我想计算一个加权表

dta = structure(list(PHHWT14 = c(530, 457, 416, 497, 395, 480, 383, 
                       420, 499, 424, 504, 497, 449, 406, 492, 470, 418, 407, 403, 362, 
                       393, 368, 423, 448, 511, 511, 423, 470, 453, 429, 439, 425, 431, 
                       443, 480, 452, 472, 406, 460, 436, 574, 456, 399, 476, 423, 501, 
                       399, 459, 396, 409, 423, 399, 383, 433, 436, 413, 403, 414, 410, 
                       337, 472, 448, 487, 442, 475, 410, 478, 483, 374, 414, 514, 422, 
                       409, 455, 464, 362, 461, 356, 464, 456, 494, 348, 464, 432, 398, 
                       426, 418, 429, 516, 363, 455, 413, 388, 508, 381, 439, 330, 385, 
                       393, 454), SEX = structure(c(2L, 1L, 2L, 2L, 1L, 2L, 2L, 1L, 
                                                    2L, 2L, 2L, 1L, 2L, 1L, 2L, 2L, 2L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 
                                                    2L, 2L, 1L, 2L, 2L, 2L, 2L, 2L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 
                                                    2L, 2L, 2L, 2L, 1L, 2L, 2L, 2L, 1L, 2L, 2L, 1L, 2L, 2L, 2L, 1L, 
                                                    2L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 1L, 2L, 2L, 1L, 2L, 2L, 1L, 
                                                    2L, 2L, 2L, 1L, 2L, 2L, 2L, 2L, 2L, 1L, 2L, 2L, 1L, 2L, 1L, 2L, 
                                                    2L, 2L, 2L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L), .Label = c("Female",  "Male"), class = "factor")), row.names = c(NA, 100L), class = "data.frame", .Names = c("PHHWT14",  "SEX"))

使用xtabs:

xtabs(PHHWT14 ~ SEX, dta) 

我会得到:

SEX
Female   Male 
10115  33490

有没有办法使用权重汇总?

dta %>% 
group_by(SEX) %>% 
summarise(n())

3 个答案:

答案 0 :(得分:3)

您也可以使用summarise_each。您的示例与summarise版本相同,但如果您想要总结其他列,则非常有用。

dta %>% 
  group_by(SEX) %>% 
  summarise_each(funs(sum))
## Source: local data frame [2 x 2]
##
##     SEX PHHWT14
## 1 Female   10115
## 2   Male   33490

答案 1 :(得分:2)

dta %>% group_by(SEX) %>%
  summarise(sum(PHHWT14))

#         SEX sum(PHHWT14)
#    1 Female        10115
#    2   Male        33490

答案 2 :(得分:1)

你的意思是按变量分组,但你也可以按重量进行调整。

通常,如果您有数字权重变量或总计上涨因子,您可以使用点向sum()函数添加其他参数: 使用dplyr:

尝试使用iris df
library(dplyr)
set.seed(1234)
df <- iris
df[,"weights"] <- rnorm(nrow(df),1,0.1 ) # generate randomized weights
head(df)

df %>%
  group_by(Species) %>%
  summarise_each(funs(sum(. * weights , na.rm = TRUE),  # Weighted Sum
                      weighted.mean(.,w = weights, na.rm = TRUE))) -> agg.df # Weighted Mean 

agg.df