R中类似透视表的输出?

R中类似透视表的输出?,r,pivot-table,reshape,R,Pivot Table,Reshape,我正在写一份报告,需要在Excel中生成许多透视表。我想有一种方法可以在R中实现这一点,这样我就可以避免使用Excel。我想像下面的屏幕截图一样输出(编辑教师姓名)。据我所知,我可以使用重塑包来计算聚合值,但我需要多次这样做,并以某种方式以正确的顺序获得所有数据。在这一点上,我应该用Excel来做。有人有什么建议或一揽子建议吗?谢谢大家! (编辑) 数据以学生、教师、学校和成长的列表开始。然后对这些数据进行汇总,得到一份教师名单及其平均班级增长率。请注意,教师随后按学校分组。到目前为止,我预见到

我正在写一份报告,需要在Excel中生成许多透视表。我想有一种方法可以在R中实现这一点,这样我就可以避免使用Excel。我想像下面的屏幕截图一样输出(编辑教师姓名)。据我所知,我可以使用重塑包来计算聚合值,但我需要多次这样做,并以某种方式以正确的顺序获得所有数据。在这一点上,我应该用Excel来做。有人有什么建议或一揽子建议吗?谢谢大家!

(编辑) 数据以学生、教师、学校和成长的列表开始。然后对这些数据进行汇总,得到一份教师名单及其平均班级增长率。请注意,教师随后按学校分组。到目前为止,我预见到的最大的问题是如何在R中获得小计和总计行(BSA1总计、总计等),因为它们与其他行的观察类型不同?您是否需要手动计算它们,并尝试以正确的顺序获取它们,以便它们显示在该组的底部



(来源:)

这里是计算位的一个swag:

set.seed(1)
school  <- sample(c("BSA1", "BSA2", "HSA1"), 100, replace=T)
teacher <- sample(c("Tom", "Dick", "Harry"), 100, replace=T)
growth <- rnorm(100, 5, 3)

myDf <- data.frame(school, teacher, growth)

require(reshape2)

aggregate(growth ~ school + teacher, data =myDf, FUN=mean)

myDf.melt <- melt(myDf, measured="growth")
dcast(myDf.melt, school + teacher ~ ., fun.aggregate=mean, margins=c("school", "teacher"))
该示例使用重塑2包来处理小计

我认为R是这项工作的合适工具。我完全理解不确定如何开始这项分析。几年前我从Excel来到R,一开始很难摸索。让我指出四个专业技巧,帮助您在堆栈溢出中获得更好的答案:

1) 提供数据,即使是模拟的:你可以看到我在回答的开头模拟了一些数据。如果你提供了这种模拟,它将a)节省我的时间b)得到一个使用你自己的数据结构的答案,而不是我想象出来的,c)其他人会回答的。我经常跳过没有数据的问题,因为我已经厌倦了猜测他们被告知的数据。我的答案很糟糕,因为我猜错了

2) 问一个明确的问题。“我如何做我的工作”不是一个明确的问题。“如何获取此示例数据并在聚合中创建小计,如此示例输出”是一个特定的问题

3) 继续问!我们都会通过练习变得更好。你试图在R中做得更多,而在Excel中做得更少,所以你的智力显然高于平均水平。继续使用R,继续提问。随着时间的推移,一切都会变得容易


4) 当你描述事物时,小心你的言辞。你在编辑过的问题中说你有一个“清单”。R中的列表是一种特定的数据结构。我怀疑你实际上有一个数据框,并且在一般意义上使用术语“列表”。这可能会造成一些混乱。它还说明了为什么要提供自己的数据

使用JD Long的模拟数据,并添加sd和计数:

   library(reshape)  # not reshape2
   cast(myDf.melt, school + teacher ~ ., margins=TRUE , c(mean, sd, length))
   school teacher     mean       sd length
1    BSA1    Dick 4.663140 3.718773     14
2    BSA1   Harry 4.310802 1.430594      9
3    BSA1     Tom 5.505247 4.045846      4
4    BSA1   (all) 4.670451 3.095980     27
5    BSA2    Dick 6.110988 2.304104     15
6    BSA2   Harry 5.007221 2.908146      9
7    BSA2     Tom 4.337063 2.789244     14
8    BSA2   (all) 5.196018 2.682924     38
9    HSA1    Dick 4.508610 2.946961     11
10   HSA1   Harry 4.890741 2.977305     13
11   HSA1     Tom 4.721124 3.193576     11
12   HSA1   (all) 4.717335 2.950959     35
13  (all)   (all) 4.886576 2.873637    100

下面是使用相对较新的数据透视表包生成此数据透视表的几种不同方法

披露:我是软件包的作者

有关更多信息,请参阅上的软件包页面以及该页面上提供的各种软件包小案例

样本数据(同上)

控制台输出:

              Average Growth  Std Dev  # of Scholars  
BSA1   Dick              4.7      3.7             14  
       Harry             4.3      1.4              9  
       Tom               5.5      4.0              4  
       Total             4.7      3.1             27  
BSA2   Dick              6.1      2.3             15  
       Harry             5.0      2.9              9  
       Tom               4.3      2.8             14  
       Total             5.2      2.7             38  
HSA1   Dick              4.5      2.9             11  
       Harry             4.9      3.0             13  
       Tom               4.7      3.2             11  
       Total             4.7      3.0             35  
Total                    4.9      2.9            100  
作为html小部件的快速透视表输出

library(pivottabler)
# arguments:  qhpvt(dataFrame, rows, columns, calculations, ...)
qpvt(myDf, c("school", "teacher"), NULL,  
     c("Average Growth"="mean(growth)", "Std Dev"="sd(growth)",
       "# of Scholars"="n()"),
     formats=list("%.1f", "%.1f", "%.0f"))
library(pivottabler)
qhpvt(myDf, c("school", "teacher"), NULL,  
     c("Average Growth"="mean(growth)", "Std Dev"="sd(growth)",
       "# of Scholars"="n()"),
     formats=list("%.1f", "%.1f", "%.0f"))
HTML小部件输出:

使用更详细的语法生成透视表

这有更多选项,例如重命名总计

library(pivottabler)
pt <- PivotTable$new()
pt$addData(myDf)
pt$addRowDataGroups("school", totalCaption="(all)")
pt$addRowDataGroups("teacher", totalCaption="(all)")
pt$defineCalculation(calculationName="c1", caption="Average Growth", 
   summariseExpression="mean(growth)", format="%.1f")
pt$defineCalculation(calculationName="c2", caption="Std Dev", 
   summariseExpression="sd(growth)", format="%.1f")
pt$defineCalculation(calculationName="c3", caption="# of Scholars", 
   summariseExpression="n()", format="%.0f")
pt  # to output to console as plain text
pt$renderPivot() # to output as a html widget
库(数据透视表)

pt很抱歉,请看一下我的包裹

生成以下输出的代码:

set.seed(1)
school  <- sample(c("BSA1", "BSA2", "HSA1"), 100, replace=T)
teacher <- sample(c("Tom", "Dick", "Harry"), 100, replace=T)
growth <- rnorm(100, 5, 3)

myDf <- data.frame(school, teacher, growth)

library(expss)
myDf %>% 
    # 'tab_cells' - variables on which statistics will be calculated
    # "|" is needed to suppress 'growth' in row labels
    tab_cells("|" = growth) %>%  
    # 'tab_cols' - variables for columns. Can be ommited
    tab_cols(total(label = "")) %>% 
    # 'tab_rows' - variables for rows.
    tab_rows(school %nest% list(teacher, "(All)"), "|" = "(All)") %>% 
    # 'method = list' is needed for statistics labels in column
    tab_stat_fun("Average Growth" = mean, 
                 "Std Dev" = sd, 
                 "# of scholars" = length, 
                 method = list) %>% 
    # finalize table
    tab_pivot()
通过knitr、RStudio viewer或Shining中的
htmlTable
输出:


我认为,目前的问题过于模糊,无法在网站上合理回答。我只能说:学习latex如果你还不知道,看看这个问题:并使用例如
plyr
restrape
cast
等基本函数以正确的格式获取数据帧。在R中获取你的输出非常容易,但你会得到文本格式的输出。布局应该在其他地方完成。你应该研究R数据帧。在R中,当然有很多简单的方法可以做到这一点,但如果你能提供数据开始时的内容,以及你想要的结果,你会得到更好、更适用的代码,那就更好了。似乎在排序方面存在一些问题,但你没说是什么。有什么问题吗?谢谢大家的评论。请阅读我对问题的编辑。谢谢!非常有帮助的回答。如果你要解决格式化问题,你会推荐使用xtable和swave吗?或者你推荐别的什么?再次感谢你,很好的说明。我变得懒惰了,只是想说:)我认为使用dcast::restrape2应该很容易,但无法让它工作,所以我恢复到cast::restrape2。哦。。。有趣。Hadley说,多功能聚合在整形2中被删除是为了让它更快:哇,这个答案太棒了。哈德利是上帝!我使用了这个“快速透视表以纯文本形式输出到控制台”方法来创建透视。是否有办法将输出保存在数据帧中。我无法获取以下错误“无法将类“c”(“数据透视表”,“R6”)”强制为data.frame”请参见:
library(pivottabler)
pt <- PivotTable$new()
pt$addData(myDf)
pt$addRowDataGroups("school", totalCaption="(all)")
pt$addRowDataGroups("teacher", totalCaption="(all)")
pt$defineCalculation(calculationName="c1", caption="Average Growth", 
   summariseExpression="mean(growth)", format="%.1f")
pt$defineCalculation(calculationName="c2", caption="Std Dev", 
   summariseExpression="sd(growth)", format="%.1f")
pt$defineCalculation(calculationName="c3", caption="# of Scholars", 
   summariseExpression="n()", format="%.0f")
pt  # to output to console as plain text
pt$renderPivot() # to output as a html widget
set.seed(1)
school  <- sample(c("BSA1", "BSA2", "HSA1"), 100, replace=T)
teacher <- sample(c("Tom", "Dick", "Harry"), 100, replace=T)
growth <- rnorm(100, 5, 3)

myDf <- data.frame(school, teacher, growth)

library(expss)
myDf %>% 
    # 'tab_cells' - variables on which statistics will be calculated
    # "|" is needed to suppress 'growth' in row labels
    tab_cells("|" = growth) %>%  
    # 'tab_cols' - variables for columns. Can be ommited
    tab_cols(total(label = "")) %>% 
    # 'tab_rows' - variables for rows.
    tab_rows(school %nest% list(teacher, "(All)"), "|" = "(All)") %>% 
    # 'method = list' is needed for statistics labels in column
    tab_stat_fun("Average Growth" = mean, 
                 "Std Dev" = sd, 
                 "# of scholars" = length, 
                 method = list) %>% 
    # finalize table
    tab_pivot()
 |       |       | Average Growth | Std Dev | # of scholars |
 | ----- | ----- | -------------- | ------- | ------------- |
 |  BSA1 |  Dick |            4.7 |     3.7 |            14 |
 |       | Harry |            4.3 |     1.4 |             9 |
 |       |   Tom |            5.5 |     4.0 |             4 |
 |       | (All) |            4.7 |     3.1 |            27 |
 |  BSA2 |  Dick |            6.1 |     2.3 |            15 |
 |       | Harry |            5.0 |     2.9 |             9 |
 |       |   Tom |            4.3 |     2.8 |            14 |
 |       | (All) |            5.2 |     2.7 |            38 |
 |  HSA1 |  Dick |            4.5 |     2.9 |            11 |
 |       | Harry |            4.9 |     3.0 |            13 |
 |       |   Tom |            4.7 |     3.2 |            11 |
 |       | (All) |            4.7 |     3.0 |            35 |
 | (All) |       |            4.9 |     2.9 |           100 |