How to make and sort an array of tuples in R

I have a couple of tuples, and I need to sort them by the second item. Here is the pseudo code:

events <- vector(mode = "list", length = 5) events[[1]] <- c(3,1.4) events[[2]] <- c(2,1.8) events[[3]] <- c(8,5.3) events[[4]] <- c(6,1.4) events[[5]] <- c(6,5.4) #sort according to second item in tuple sort(events) events 

I would like to get a result that would be as follows:

 [c(3,1.4),c(6,1.4),c(2,1.8),c(8,5.3),c(6,5.4)] 
+4
source share
1 answer

One way is to extract the second elements of each component of the list using [ , and then order them and use that order to sort events .

First create the data object that you have:

 events <- vector(mode = "list", length = 5) events[[1]] <- c(3,1.4) events[[2]] <- c(2,1.8) events[[3]] <- c(8,5.3) events[[4]] <- c(6,1.4) events[[5]] <- c(6,5.4) 

The next step is to extract the second elements of each of the components of the list. We can do this using sapply() to apply the [ . 2 below refers to the second element.

 > sapply(events, `[`, 2) [1] 1.4 1.8 5.3 1.4 5.4 

Then we can get the ordering of these second elements using order()

 > ord <- order(sapply(events, `[`, 2)) > ord [1] 1 4 2 3 5 

What can we then use to order the events list

 > events[ord] [[1]] [1] 3.0 1.4 [[2]] [1] 6.0 1.4 [[3]] [1] 2.0 1.8 [[4]] [1] 8.0 5.3 [[5]] [1] 6.0 5.4 
+5
source

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


All Articles