R排序sort、order、rank、arrange
Ø sort
sort(x, decreasing = FALSE, ...)
## Default S3 method:
sort(x, decreasing = FALSE, na.last = NA, ...)
sort.int(x, partial = NULL, na.last = NA, decreasing = FALSE,
method = c("shell", "quick"), index.return = FALSE)
is.unsorted(x, na.rm = FALSE, strictly = FALSE)
> x<-c(12,9,5,7,15,NA,7,8,NA,13)
> sort(x,na.last = TRUE)
[1] 5 7 7 8 9 12 13 15 NA NA
> sort(x,na.last = FALSE)
[1] NA NA 5 7 7 8 9 12 13 15
> sort(x,na.last = NA)
[1] 5 7 7 8 9 12 13 15
Ø order
order(..., na.last = TRUE, decreasing = FALSE) 位置索引
> d<-data.frame(x=c(13,45,13,45,13),y=c(3,1,2,2,3),t=c(56,7,68,3,1))
> d[ order( d$x,d$y ), ] x升序,y升序
x y t
3 13 2 68
1 13 3 56
5 13 3 1
2 45 1 7
4 45 2 3
> d[ order( -d$x,d$y ), ] x降序,y升序
x y t
2 45 1 7
4 45 2 3
3 13 2 68
1 13 3 56
5 13 3 1
Ø rank
rank(x, na.last = TRUE,
ties.method = c("average", "first", "random", "max", "min"))
> x<-c(12, 5, 7, 15, NA, 7, 12)
> sort(x,na.last = TRUE)
[1] 5 7 7 12 12 15 NA
> rank(x,na.last = TRUE) 位置索引
[1] 4.5 1 2.5 6 7 2.5 4.5
Ø arrange
> head(arrange(mtcars, cyl, disp)) 多个关键字排序
mpg cyl disp hp drat wt qsec vs am gear carb
1 33.9 4 71.1 65 4.22 1.835 19.90 1 1 4 1
2 30.4 4 75.7 52 4.93 1.615 18.52 1 1 4 2
3 32.4 4 78.7 66 4.08 2.200 19.47 1 1 4 1
4 27.3 4 79.0 66 4.08 1.935 18.90 1 1 4 1
5 30.4 4 95.1 113 3.77 1.513 16.90 1 1 5 2
6 22.8 4 108.0 93 3.85 2.320 18.61 1 1 4 1
> head(arrange(mtcars, cyl, desc(disp)))
mpg cyl disp hp drat wt qsec vs am gear carb
1 24.4 4 146.7 62 3.69 3.190 20.00 1 0 4 2
2 22.8 4 140.8 95 3.92 3.150 22.90 1 0 4 2
3 21.4 4 121.0 109 4.11 2.780 18.60 1 1 4 2
4 26.0 4 120.3 91 4.43 2.140 16.70 0 1 5 2
5 21.5 4 120.1 97 3.70 2.465 20.01 1 0 3 1
6 22.8 4 108.0 93 3.85 2.320 18.61 1 1 4 1