ToNoY
ToNoY

Reputation: 1378

How to sort data within a "list" using ORDER function in R

I have created a list of data as shown below

> sites
[[1]]
   ANLL_ID      lat     long      X       Y Depth_m       
15      B3 23.78038 90.63857 259364 2631912    94.2 
16      B4 23.78038 90.63857 259364 2631912    29.9 
17      B5 23.78038 90.63857 259364 2631912    47.1 
18      B6 23.78038 90.63857 259364 2631912    51.5 
19      B7 23.78038 90.63857 259364 2631912     6.0 
20      B8 23.78038 90.63857 259364 2631912    10.2 
21      B9 23.78038 90.63857 259364 2631912    25.6 


[[2]]
   ANLL_ID   lat   long      X       Y Depth_m                    
22      C1 23.79 90.611 256572 2633025      15 
23      C2 23.79 90.611 256572 2633025       8  
24      C3 23.79 90.611 256572 2633025      10  
25      C4 23.79 90.611 256572 2633025      94  
26      C5 23.79 90.611 256572 2633025      53  

... ...

If I want to order/sort (keeping all variables) the long list using sapply according to 'Depth_m' as:

sites.srt<- lapply(1:length(sites),
                   function(i) sites[order(sites[[i]]$Depth_m),])

But R throws an error-

Error in sites[order(sites[[i]]$Depth_m), ] : 
  incorrect number of dimensions

I know it's happening because the data is as LIST, NOT as a dataframe. I can turn it into a dataframe. But keeping the data as a list makes it easier for me to do further processing. Is there any way to sort within the lists- [[1]], [[2]], ... ... [[15]]?

Upvotes: 1

Views: 1534

Answers (1)

James
James

Reputation: 66844

If I understand correctly

lapply(sites, function(x) x[order(x$Depth_m),])

will give you what you want.

Upvotes: 2

Related Questions