使用addmargins对r中表上的行和列进行排序
我使用下面的代码创建了一个表。我想对行和列进行排序,使其从高到低,总和在底部使用addmargins对r中表上的行和列进行排序,r,R,我使用下面的代码创建了一个表。我想对行和列进行排序,使其从高到低,总和在底部 #Some data DeptEmployees <- data.frame(Department = c("Sales", "Sales", "HR","Sales", "HR", "IT","IT", "HR", "Sales"), Country=c( "USA", "Canada", "UK", "UK", "UK", "USA", "USA", "Canada", "UK")) #Create the
#Some data
DeptEmployees <- data.frame(Department = c("Sales", "Sales", "HR","Sales", "HR", "IT","IT", "HR", "Sales"), Country=c( "USA", "Canada", "UK", "UK", "UK", "USA", "USA", "Canada", "UK"))
#Create the table
DeptTotals<-addmargins(table(DeptEmployees[, c("Department", "Country")]))
DeptTotals
#一些数据
DeptEmployees你们非常接近。order语句后面需要有一个逗号,因为您正在重新排列deptotals
的行。此外,该表的结构是4x4,其中Department
作为与rownames类似的命名列
在这里的帖子的帮助下,我终于找到了答案。我遇到的一个问题是,当我对rowsum列进行排序时,columnsum行被重新排序
#Create the table with the rowsum column
DeptTotals<-addmargins(table(DeptEmployees[, c("Department", "Country")]),2)
# Reorder the row sum column so it is descending
DeptTotalReordered <- DeptTotals[order(DeptTotals[,4],decreasing=T),]
# add the sumcolumn row as a final step to ensure it is at the bottom of the table
DeptTotalReorderedWithColumnSumRow <- addmargins (DeptTotalReordered,1)
DeptTotalReorderedWithColumnSumRow
#创建具有行和列的表
谢谢你的帮助,这让我找到了答案。
#Create the table with the rowsum column
DeptTotals<-addmargins(table(DeptEmployees[, c("Department", "Country")]),2)
# Reorder the row sum column so it is descending
DeptTotalReordered <- DeptTotals[order(DeptTotals[,4],decreasing=T),]
# add the sumcolumn row as a final step to ensure it is at the bottom of the table
DeptTotalReorderedWithColumnSumRow <- addmargins (DeptTotalReordered,1)
DeptTotalReorderedWithColumnSumRow