【问题标题】:Good ways to code complex tabulations in R?在 R 中编写复杂表格的好方法?
【发布时间】:2010-11-30 20:50:24
【问题描述】:

有人对如何在 R 中编写复杂的表格有任何好的想法吗?

恐怕我对此可能有点含糊,但我想设置一个脚本来创建一堆复杂性类似于美国统计摘要的表。

例如:http://www.census.gov/compendia/statab/tables/09s0015.pdf

我想避免一大堆 rbind 和 hbind 语句。

SAS,听说有一种建表规范语言;我想知道R 是否有类似的力量?

谢谢!

【问题讨论】:

    标签: r statistics data-visualization


    【解决方案1】:

    Here is an interesting blog posting on this topic.作者试图创建一份类似于联合国世界人口展望:2008 年修订报告的报告。

    希望对您有所帮助, 查理

    【讨论】:

    • 查理:这不是我答案底部的同一个链接吗?
    • 嗨,Shane,你是对的,我很抱歉;我没有注意到你的链接。
    【解决方案2】:

    另一个选项是 plyr 包。

    library(plyr)
    names(airquality) <- tolower(names(airquality))
    ddply(airquality, "month", function(x){
        with(x, c(meantemp = mean(temp), maxtemp = max(temp), nonsense = max(temp) - min(solar.r)))
    })
    

    【讨论】:

      【解决方案3】:

      您似乎想对某些数据应用多种不同的计算,并按一个字段(在示例中按状态)对其进行分组?

      有很多方法可以做到这一点。见this related question

      您可以使用 Hadley Wickham 的 reshape 软件包(请参阅 reshape homepage)。例如,如果您希望将平均值、总和和计数函数应用于按值分组的某些数据(这没有意义,但它使用来自 reshape 的空气质量数据):

      > library(reshape)
      > names(airquality) <- tolower(names(airquality))
      > # melt the data to just include month and temp
      > aqm <- melt(airquality, id="month", measure="temp", na.rm=TRUE)
      > # cast by month with the various relevant functions
      > cast(aqm, month ~ ., function(x) c(mean(x),sum(x),length(x)))
        month X1   X2 X3
      1     5 66 2032 31
      2     6 79 2373 30
      3     7 84 2601 31
      4     8 84 2603 31
      5     9 77 2307 30
      

      或者您可以使用by() 函数。索引将代表州的位置。在您的情况下,您可以应用自己的函数来执行多项任务(取决于您的需要),而不是应用一个函数(例如平均值):例如,function(x) { c(mean(x), length(x)) }。然后在输出上运行do.call("rbind"(例如)。

      此外,您可能会考虑使用报告包,例如 Sweave(带有 xtable)或 Jeffrey Horner's brew package。有一个great post on the learnr blog about creating repetitive reports 显示如何使用它。

      【讨论】:

      • 只是一个简短的评论 - each 也负责列名:cast(aqm, month ~ ., each(mean, sum, length)。而且,最简单的就是使用ccast(aqm, month ~ ., c(mean, sum, length)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-10-09
      • 1970-01-01
      • 2015-06-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多