下面是使用較新的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小組件輸出:
![enter image description here](https://i.stack.imgur.com/pF7zv.png)
生成透視表使用更詳細的語法
這具有更多的選項,例如重命名總數。
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小組件輸出:
![enter image description here](https://i.stack.imgur.com/MP1mf.png)
因爲目前的情況是不明確,合理的網站就在這裏,我認爲回答這個問題。我只能說:學習乳膠,如果你不知道這一點,看看這個問題:http://stackoverflow.com/questions/5465314/tools-for-making-latex-tables-in-r並獲取數據幀使用例如'plyr'或'reshape'的正確格式或者像'cast'這樣的基本函數等等。獲得你輸出的內容在R中很容易,但是你會以文本格式得到它。佈局應該在其他地方完成。 –
你應該看看R數據幀。 – ATMathew
當然在R中有很多簡單的方法可以做到這一點,但如果你可以提供什麼數據開始,那麼除了你想要的結果之外,你會得到更好更適用的代碼會更好。 – John