获取连续数据(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)))
但是是否有一种一次性方法可以返回上述矩阵?谢谢!
With df:
df <- data.frame(value=abs(rnorm(100, 25, 5)), status=sample(0:1,100,replace=T))
df$value[sample(1:100,5)] <- NA
I need to get a frequency (percentage) table (better return a matrix) like the following:
value | status(0) status(1)
----------------------------
<=25 | 23 (23%) 20 (20%)
>25 | 27 (27%) 25 (25%)
NA | 3 (3%) 2 (2%)
I can do this using:
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)))
But would there be a one-time way to return a matrix as above? Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
(当然,如果您愿意,可以将其合并为 1 行,但为了更好的可读性,我将其保留为 2 行。)
编辑:如果您想要一个格式化为频率的比例表,您可以执行以下操作:
(Of course this can be combined into 1 line if you want, but I left it as 2 here for better readability.)
EDIT: And if you want a table of proportions, formatted as frequencies, you can do:
另一种解决方案使用
reshape2
。Another solution using
reshape2
.