数据操作之排序

R

order(X, na.last=TRUE, decreasing=FALSE)

返回值: X排好序的下标向量
na.last 控制空值NA排在最前还是最后,默认最后
desceasing 控制升序还是降序排列
 
例子:
#vector
X <- c(7,4,5,2,8,1,9,3)
order(X)

[1] 6 4 8 2 3 1 5 7
 
X[order(X)]

[1] 1 2 3 4 5 7 8 9
 
X[order(X, decreasing=TRUE)]

[1] 9 8 7 5 4 3 2 1
 
 
order(-X) # '-' equals decreasing=TRUE
[1] 7 5 1 3 2 4 8 6
#vector

#dataframe.

X <- c(7,4,5,3,8,1,9,3)

Y <- c(50, 80, 30, 70, 20, 10, 40, 90)

order(X, Y) #only print X's order, no Y's

[1] 6 4 8 2 3 1 5 7

table_1 <- data.frame(x=X, y=Y)

table_1

  x  y
1 7 50
2 4 80
3 5 30
4 3 70
5 8 20
6 1 10
7 9 40
8 3 90
 
order(table_1$x, table_1$y) #X asc, Y asc, print the row number's sequence

[1] 6 4 8 2 3 1 5 7
 
table_1[order(table_1$x, -table_1$y),] #X asc, Y desc
  x  y
6 1 10
8 3 90
4 3 70
2 4 80
3 5 30
1 7 50
5 8 20
7 9 40
 
table_1[order(-table_1$x, table_1$y), ] #X desc, Y asc

  x  y
7 9 40
5 8 20
1 7 50
3 5 30
2 4 80
4 3 70
8 3 90
6 1 10
 
table_1[order(-table_1$x, -table_1$y), ] #X desc, Y desc

  x  y
7 9 40
5 8 20
1 7 50
3 5 30
2 4 80
8 3 90
4 3 70
6 1 10

  

posted on 2016-03-23 15:01  MartinChau  阅读(194)  评论(0编辑  收藏  举报

导航