더북(TheBook)

order()

order( )는 주어진 인자를 정렬하기 위한 각 요소의 색인을 반환한다. 함수 프로토타입은 ‘4.5.2 orderBy( )’ 절에서 이미 보였으므로 생략한다.

다음은 임의의 값을 저장한 벡터 x를 정렬하기 위한 순서를 반환한 예다. order(x)는 x[order(x)]가 정렬되어 있게 하기 위한 색인이다.

> x <- c(20, 11, 33, 50, 47)
> order(x)
[1] 2 1 3 5 4

내림차순으로 정렬한 결과를 얻고 싶다면 decreasing=TRUE를 지정한다.

> x <- c(20, 11, 33, 50, 47)
> order(x, decreasing=TRUE)
[1] 4 5 3 1 2

order( )가 정렬된 순서를 반환한다는 점을 이용해 데이터 프레임을 정렬할 수 있다. 다음은 아이리스 데이터를 Sepal.Length에 따라 정렬한 예다.

> iris[order(iris$Sepal.Length), ]
   Sepal.Length Sepal.Width Petal.Length Petal.Width Species
14          4.3          3.0         1.1         0.1  setosa
9           4.4          2.9         1.4         0.2  setosa
39          4.4          3.0         1.3         0.2  setosa
43          4.4          3.2         1.3         0.2  setosa
42          4.5          2.3         1.3         0.3  setosa
4           4.6          3.1         1.5         0.2  setosa
...

결과를 보면 9행, 39행, 43행의 Sepal.Length가 모두 같다. 이와 같이 Sepal.Length가 같을 경우 Petal.Length의 순서에 따라 정렬하려면 다음과 같이 Petal.Length를 추가적인 인자로 order( )에 넘기면 된다.

> iris[order(iris$Sepal.Length, iris$Petal.Length), ]
   Sepal.Length Sepal.Width Petal.Length Petal.Width Species
14          4.3         3.0          1.1         0.1  setosa
39          4.4         3.0          1.3         0.2  setosa
43          4.4         3.2          1.3         0.2  setosa
9           4.4         2.9          1.4         0.2  setosa
42          4.5         2.3          1.3         0.3  setosa
23          4.6         3.6          1.0         0.2  setosa
...

보다시피 9행, 39행, 43행이었던 순서가 Petal.Length의 크기에 따라 39행, 43행, 9행으로 바뀌었다.