【问题标题】:nested table with different variables as the rows with r具有不同变量的嵌套表作为具有 r 的行
【发布时间】:2013-08-12 17:33:36
【问题描述】:

我正在尝试使用 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 包还是其他?

【问题讨论】:

  • 您可以使用ftabletable。详情见?ftable
  • 也许reporttools 包会有所帮助,尤其是?tableNominal
  • @Metrics 使用 ftable 有没有办法计算百分比?
  • 是的,您可以查看here 了解概览

标签: r knitr nested-table


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2023-03-27
    • 2016-07-26
    • 1970-01-01
    • 2020-01-11
    • 2021-08-15
    • 2016-06-21
    • 1970-01-01
    • 1970-01-01
    • 2021-11-11
    相关资源
    最近更新 更多