Frequency tables with weighted data in R

馋奶兔 提交于 2019-12-03 11:40:23

You can use function svytable from package survey, or wtd.table from rgrs.

EDIT : rgrs is now called questionr :

df <- data.frame(var = c("A", "A", "B", "B"), wt = c(30, 10, 20, 40))

library(questionr)
wtd.table(x = df$var, weights = df$wt)
#  A  B 
# 40 60

That's also possible with dplyr :

library(dplyr)
count(x = df, var, wt = wt)
# # A tibble: 2 x 2
#        var     n
#     <fctr> <dbl>
#   1      A    40
#   2      B    60

Using data.table you could do:

# using the same data as Victorp
setDT(df)[, .(n = sum(wt)), var] 

   var  n
1:   A 40
2:   B 60

You can also use tablefreq from package freqweights:

df <- data.frame(var = c("A", "A", "B", "B"), wt = c(30, 10, 20, 40))

library(freqweights)

tablefreq(df, "var", "wt")

A tibble: 2 x 2
var    freq
<fct> <dbl>
1 A        40
2 B        60
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!