【问题标题】:Relative weighted frequencies/proportions in dplyrdplyr 中的相对加权频率/比例
【发布时间】:2020-01-30 22:29:31
【问题描述】:

我正在尝试获得一种 dplyr 方法来制作数据加权的相对表或比例。我正在阅读有关 dplyr 中相对频率/比例的线程,其中一个答案在 data.table 中

library("data.table")
cars_dt <- as.data.table(mtcars)
cars_dt[, .(n = .N), keyby = .(am, gear)][, freq := prop.table(n) , by = "am"]

我知道如何通过用sum(weight) 代替.N 来衡量这种方法。我看不到如何将权重应用于其他线程中提出的 dplyr 方法。

【问题讨论】:

  • 你期待看到什么?

标签: r dplyr


【解决方案1】:

一位同事给了我答案

library(survey)
# load data
data(api)

x <- apistrat

## data.tab
x <- data.table::data.table(x)

#unweighted proportion of share of schools meeting target by being year round
x[ , .(p = .N) , keyby = .(comp.imp, yr.rnd)][ , .(comp.imp, per = p/sum(p)) , by = yr.rnd ]
   yr.rnd comp.imp       per
1:     No       No 0.4413408
2:     No      Yes 0.5586592
3:    Yes       No 0.2380952
4:    Yes      Yes 0.7619048
# weighted (weight is pw)
x[ , .(p = sum(pw)) , keyby = .(comp.imp, yr.rnd)][ , .(comp.imp, per = p/sum(p)) , by = yr.rnd ]
   yr.rnd comp.imp       per
1:     No       No 0.3677785
2:     No      Yes 0.6322215
3:    Yes       No 0.1973814
4:    Yes      Yes 0.8026186

## dplyr

x %>% group_by(yr.rnd) %>% count(comp.imp , wt = pw) %>% mutate(per = n/sum(n))
# A tibble: 4 x 4
# Groups:   yr.rnd [2]
  yr.rnd comp.imp     n   per
  <fct>  <fct>    <dbl> <dbl>
1 No     No       1965. 0.368
2 No     Yes      3378. 0.632
3 Yes    No        168. 0.197
4 Yes    Yes       684. 0.803

【讨论】:

    猜你喜欢
    • 2014-08-25
    • 2020-04-24
    • 1970-01-01
    • 2022-08-18
    • 1970-01-01
    • 1970-01-01
    • 2020-10-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多