0

我正在尝试使用tablesr 中的包制作一个嵌套表,然后可以将其添加到 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包装还是其他?

4

1 回答 1

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
于 2013-08-12T17:55:12.500 回答