How to sort alphabetically rows of a data frame?
本问题已经有最佳答案,请猛点这里访问。
我正在按字母顺序对
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 | best <- function(state){ HospitalName<-vector() StateName<-vector() HeartAttack<-vector() k<-1 outcome<-read.csv("outcome-of-care-measures.csv",colClasses="character") temp<-(outcome[,c(2,7,11,17,23)]) for (i in 1:nrow(temp)){ if(identical(state,temp[i,2])==TRUE){ HospitalName[k]<-temp[i,1] StateName[k]<-temp[i,2] HeartAttack[k]<-as.numeric(temp[i,4]) k<-k+1 }} frame<-data.frame(cbind(HospitalName,StateName,HeartAttack)) library(dplyr) frame %>% group_by(as.numeric(as.character(frame[,3]))) %>% arrange(frame[,1]) } Output: HospitalName StateName HeartAttack 1 FORT DUNCAN MEDICAL CENTER TX 8.1 2 TOMBALL REGIONAL MEDICAL CENTER TX 8.5 3 CYPRESS FAIRBANKS MEDICAL CENTER TX 8.7 4 DETAR HOSPITAL NAVARRO TX 8.7 5 METHODIST HOSPITAL,THE TX 8.8 6 MISSION REGIONAL MEDICAL CENTER TX 8.8 7 BAYLOR ALL SAINTS MEDICAL CENTER AT FW TX 8.9 8 SCOTT & WHITE HOSPITAL-ROUND ROCK TX 8.9 9 THE HEART HOSPITAL BAYLOR PLANO TX 9 10 UT SOUTHWESTERN UNIVERSITY HOSPITAL TX 9 .. ... ... ... Variables not shown: as.numeric(as.character(frame[, 3])) (dbl) |
输出不包含心脏病专栏,我不明白为什么?
一种带有
1 2 3 4 | library(dplyr) df %>% group_by(x) %>% arrange(c) |
或者正如@akrun在下面的评论中提到的
1 2 | df %>% arrange(x,c) |
号
如果您对分组不感兴趣。取决于你想要什么。
输出:
1 2 3 4 5 6 7 8 9 | Source: local data frame [5 x 2] Groups: x x c 1 2 A 2 2 D 3 3 B 4 3 C 5 5 E |
在基R中还有另一个解决方案,但是只有当X列按原样排序时,或者如果您不介意更改它的顺序时,它才会起作用:
1 2 3 4 5 6 7 | > df[order(df$x, df$c), , drop = FALSE] x c 2 2 A 1 2 D 4 3 B 3 3 C 5 5 E |
。