html - R: output a pivot-like table with subtotals -
i'm trying make cross tabulation in r, , having output resemble as possible i'd in excel pivot table. objective replace report made manually excel , word 1 automated r markdown; data wrangling , charts have been taken care of tables missing. so, given code:
set.seed(2) df<-data.frame("ministry"=paste("ministry ",sample(1:3,20,replace=t)),"department"=paste("department ",sample(1:3,20,replace=t)),"program"=paste("program ",sample(letters[1:20],20,replace=f)),"budget"=runif(20)*1e6) library(tables) library(dplyr) arrange(df,ministry,department,program) tabular(ministry*department~((count=budget)+(avg=(mean*budget))+(total=(sum*budget))),data=df) which yields (actual data more complicated):
avg total ministry department count budget budget ministry 1 department 1 5 479871 2399356 department 2 1 770028 770028 department 3 1 184673 184673 ministry 2 department 1 2 170818 341637 department 2 1 183373 183373 department 3 3 415480 1246440 ministry 3 department 1 0 nan 0 department 2 5 680102 3400509 department 3 2 165118 330235 this close excel results. need display subtotals, (generated in excel using exact same data):

is possible @ in r (without manually coding table cell-by-cell)?
thanks!
replace left hand side with:
ministry * (department + 1) + 1 that is, try this:
tabular(ministry * (department + 1) + 1 ~ ((count = budget) + (avg = (mean * budget)) + (total = (sum * budget))), data = df) giving:
avg total ministry department count budget budget ministry 1 department 1 5 479871 2399356 department 2 1 770028 770028 department 3 1 184673 184673 7 479151 3354057 ministry 2 department 1 2 170818 341637 department 2 1 183373 183373 department 3 3 415480 1246440 6 295242 1771449 ministry 3 department 1 0 nan 0 department 2 5 680102 3400509 department 3 2 165118 330235 7 532963 3730744 20 442813 8856250 update: correction.
Comments
Post a Comment