获得连续数据(R)频率表的更好方法



带有df:

df <- data.frame(value=abs(rnorm(100, 25, 5)), status=sample(0:1,100,replace=T))
df$value[sample(1:100,5)] <- NA

我需要得到一个频率(百分比(表(最好返回一个矩阵(,如下所示:

value | status(0)  status(1)
----------------------------
 <=25 |  23 (23%)   20 (20%)
  >25 |  27 (27%)   25 (25%)
   NA |   3  (3%)    2  (2%)

我可以使用:

br <- seq(0, 50, 25)
with(df, summary(cut(value[status==0], br, labels=br[-1],
     include.lowest=T, ordered_result=T)))
with(df, summary(cut(value[status==1], br, labels=br[-1],
     include.lowest=T, ordered_result=T)))

但是,是否有一种一次性的方法可以返回如上所述的矩阵?谢谢

df$value.cut = cut(df$value, breaks=c(0, 25, 100))
> with(df, table(value.cut, status, useNA='ifany'))
          status
value.cut   0  1
  (0,25]   26 19
  (25,100] 26 24
  <NA>      3  2

(当然,如果你愿意,可以将其组合成1行,但为了更好的可读性,我在这里将其保留为2行。(

编辑:如果你想要一个比例表,格式化为频率,你可以这样做:

df.tab = with(df, table(value.cut, status, useNA='ifany'))
df.tab[,] = paste(df.tab, ' (', 100*prop.table(df.tab), '%)', sep='')
> df.tab
          status
value.cut  0        1       
  (0,25]   26 (26%) 19 (19%)
  (25,100] 26 (26%) 24 (24%)
  <NA>     3 (3%)   2 (2%)

另一个使用reshape2的解决方案。

library(reshape2)
dcast(df, cut(value, breaks = c(0, 25, 100)) ~ status)

最新更新