Hi, Check if this works: library(reshape2) res1 <- acast(FLSAdata_melt, ViolationDesc + ReasonDesc ~ variable, sum, margins=TRUE)[,-4] res2 <- within(as.data.frame(res1),`Count of Case ID` <- dcast(FLSAdata_melt, ViolationDesc + ReasonDesc ~ variable, length, margins=TRUE)[,3])[,c(4,1:3)] colnames(res2)[2:4] <- paste("Sum of",colnames(res2)[2:4]) rownames(res2)[length(rownames(res2))] <- "Grand Total" indx <- grepl("all",rownames(res2)) ord1 <- unlist(tapply(seq_len(nrow(res2)),list(cumsum(c(TRUE,diff(indx)<0))),FUN=function(x) c(tail(x,1),head(x,-1)) ),use.names=FALSE) res3 <- res2[ord1,] rownames(res3) <- gsub("\\_\\(all\\)","",rownames(res3))
A.K. On Thursday, February 6, 2014 4:46 PM, bcrombie <bcrom...@utk.edu> wrote: Based on the following code, how can I add a column to this pivot table output that will count CaseID's for each variable sum? CaseID is a factor. # library(reshape) # FLSA_Violation_Reason_melt <- melt(FLSA_ViolRsnfixed, # id=c("CaseID", "ViolationDesc", "ReasonDesc"), # measure=c("BW_Due", "BW_ATP", "EEs_Rep")) # # FLSA_Violation_Reason_cast <- cast(FLSA_Violation_Reason_melt, # ViolationDesc + ReasonDesc ~ variable, # sum, margins=TRUE) Thank you. -- View this message in context: http://r.789695.n4.nabble.com/count-and-sum-simultaneously-in-R-pivot-table-tp4684896.html Sent from the R help mailing list archive at Nabble.com. ______________________________________________ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code. ______________________________________________ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.