2011-11-02 64 views
7

用df:爲連續數據(R)獲取頻率表的更好方法?

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

我需要獲得一個頻率(百分比)表(更好的回報矩陣)像下面這樣:

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))) 

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

我可以利用這樣做

但是會有一種一次性返回上述矩陣的方法嗎?謝謝!

回答

11
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%) 
+3

而且,如果您不想指定左和右截斷點,請設置'breaks = c(-Inf,25,Inf)'。 –

+0

好的提示。我總是忘記那個,我自己。 –

+0

謝謝!應該已經知道table()更好。 :) – Rock

2

另一種解決方案使用reshape2

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

謝謝!學習新的每一天:) – Rock