下面是使用相对较新的 pivottabler 包生成它的几种不同方法。
披露:我是包作者。
有关更多信息,请参阅CRAN上的包页面以及该页面上提供的各种包小插曲。
样本数据(同上)
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(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"))
控制台输出:
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)
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
HTML 小部件输出: