我想按字母顺序排序c
if x[i]== x[i+1]
。我使用了order()
函数,但它也更改了x
列。我想订购整行:
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)
输出不包含HeartAttack列,我不明白为什么?
答案 0 :(得分:3)
dplyr
的一个解决方案:
library(dplyr)
df %>%
group_by(x) %>%
arrange(c)
或者@Akrun在下面的评论中提及
df %>%
arrange(x,c)
如果您对分组不感兴趣。取决于你想要的东西。
输出:
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列时,或者如果您不介意改变它的顺序,它才会起作用:
> 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