带有不同变量的嵌套表作为带r的行

时间:2013-08-12 17:33:36

标签: r knitr nested-table

我正在尝试使用r中的tables包创建一个嵌套表,然后可以将其添加到knitr文档中。

我想创建一个表,其中每一行是数据集中的不同分类变量,每列是每个响应选项的频率和百分比。

我希望结果看起来像这样

Variable     1-5 times        6-10 times      11-15 times
           freq    Percent  freq   percent   freq  percent    
eating       5       33       5      33       5       33
drinking     5       33       5      33       5       33

以下是一些应该允许生成上表的代码。

eating <- c("1-5 times", "1-5 times", "1-5 times","1-5 times","1-5 times", "6-10 times","6-10 times","6-10 times","6-10 times","6-10 times", "11-15 times","11-15 times","11-15 times","11-15 times","11-15 times")
drinking<-c("1-5 times", "1-5 times", "1-5 times","1-5 times","1-5 times", "6-10 times","6-10 times","6-10 times","6-10 times","6-10 times", "11-15 times","11-15 times","11-15 times","11-15 times","11-15 times")
eating<-factor(eating)
drinking<-factor(drinking)
df<-data.frame(eating,drinking)

有谁知道这样做的方法?使用tables包还是别的?

1 个答案:

答案 0 :(得分:0)

这不是你要求的,但足够接近:

library(plyr)
x<-ddply(df,.(eating,drinking),summarize,freq=length(eating))
x$perc<-with(x,(100*freq/sum(freq)))

   > x
       eating    drinking freq     perc
1   1-5 times   1-5 times    5 33.33333
2 11-15 times 11-15 times    5 33.33333
3  6-10 times  6-10 times    5 33.33333