How to use order to sort 2d in R

An awkwardly simple problem, but I cannot reduce order () to my will.

I have several data pairs (x, y), I just want to order on x and follow for y. For instance.

2, 1 3, 2 1, 3 

changes to:

 1, 3 2, 1 3, 2 
+4
source share
2 answers

In R, order() returns the row index vector. In your example:

 > order(data$x) [1] 3 1 2 

Which you can interpret as "the lowest value on line 3, the second lowest on line 1", etc. It is important to note that it does not in any way alter the data structure. To get a data frame sorted by x using order() , you can simply use:

 > data[order(data$x),] xy 3 1 3 1 2 1 2 3 2 
+1
source

In R, order (vector) will give you pointers in the required order. Using these pointers, you can reorder your vectors. Here are the commands for your example:

 df <- data.frame(x=c(2,3,1), y=c(1,2,3) ) df[order(df$x), ] 
0
source

Source: https://habr.com/ru/post/1502729/


All Articles