作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在生成一个 ftable(通过在 xtabs 命令的结果上运行 ftable)并且我得到以下信息。
Var1 Var2
date group
2007-01-01 q1 1 9
q2 2 8
q3 3 7
2007-01-02 q1 6 6
q2 7 5
q3 8 4
date group Var1 Var2
2007-01-01 q1 1 9
2007-01-01 q2 2 8
2007-01-01 q3 3 7
2007-01-02 q1 6 6
2007-01-02 q2 7 5
2007-01-02 q3 8 4
最佳答案
你可以通过以下方式完成这项工作:
> # from ?ftable
> r <- ftable(Titanic, row.vars = 1:3)
> r
Survived No Yes
Class Sex Age
1st Male Child 0 5
Adult 118 57
... snip ...
Female Child 0 0
Adult 3 20
>
> # long format
> as.data.frame(r)
Class Sex Age Survived Freq
1 1st Male Child No 0
2 2nd Male Child No 0
3 3rd Male Child No 35
... snip ...
30 2nd Female Adult Yes 80
31 3rd Female Adult Yes 76
32 Crew Female Adult Yes 20
>
> # wide format, but do not care the col name
> data.frame(expand.grid(rev(attr(r, "row.vars"))), unclass(r))
Age Sex Class X1 X2
1 Child Male 1st 0 5
2 Adult Male 1st 118 57
3 Child Female 1st 0 1
... snip ...
14 Adult Male Crew 670 192
15 Child Female Crew 0 0
16 Adult Female Crew 3 20
>
> # using reshape2 library
> library(reshape2)
> dcast(as.data.frame(r), as.formula(paste(paste(names(attr(r, "row.vars")), collapse="+"), "~", paste(names(attr(r, "col.vars"))))))
Using Freq as value column: use value_var to override.
Class Sex Age No Yes
1 1st Male Child 0 5
2 1st Male Adult 118 57
3 1st Female Child 0 1
... snip ...
14 Crew Male Adult 670 192
15 Crew Female Child 0 0
16 Crew Female Adult 3 20
关于r - 将 ftable(列联表)转换为 R 中的数据帧,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6462769/
我是一名优秀的程序员,十分优秀!