How to sort a list that contains single sub-elements in decreasing order in R?

R ProgrammingServer Side ProgrammingProgramming

<p>Just like a list can have multiple elements, the elements of the list can have multiple sub-elements and the size of those elements may vary as well hence a list with single sub-elements is also possible. If we have such type of list then we can sort that list in decreasing order by using order function but we also need to unlist those elements.</p><h2>Example</h2><p>Consider the below list &minus;</p><p><a class="demo" href="http://tpcg.io/PdEtVgLL" rel="nofollow" target="_blank">&nbsp;Live Demo</a></p><pre class="prettyprint notranslate">x1&lt;-500 x2&lt;-245 x3&lt;-128 x4&lt;-325 x5&lt;-854 x6&lt;-329 x7&lt;-742 x8&lt;-214 x9&lt;-374 x10&lt;-524 List1&lt;-list(x1,x2,x3,x4,x5,x6,x7,x8,x9,x10) List1</pre><h2>Output</h2><pre class="result notranslate">[[1]] [1] 500 [[2]] [1] 245 [[3]] [1] 128 [[4]] [1] 325 [[5]] [1] 854 [[6]] [1] 329 [[7]] [1] 742 [[8]] [1] 214 [[9]] [1] 374 [[10]] [1] 524</pre><p>Decreasing the elements of List1 &minus;</p><h2>Example</h2><pre class="prettyprint notranslate">List1[order(unlist(List1),decreasing=TRUE)]</pre><h2>Output</h2><pre class="result notranslate">[[1]] [1] 854 [[2]] [1] 742 [[3]] [1] 524 [[4]] [1] 500 [[5]] [1] 374 [[6]] [1] 329 [[7]] [1] 325 [[8]] [1] 245 [[9]] [1] 214 [[10]] [1] 128</pre><p>Let&rsquo;s have a look at another example &minus;</p><h2>Example</h2><p><a class="demo" href="http://tpcg.io/ujw7SaKR" rel="nofollow" target="_blank">&nbsp;Live Demo</a></p><pre class="prettyprint notranslate">y1&lt;-241 y2&lt;-215 y3&lt;-421 y4&lt;-295 y5&lt;-371 y6&lt;-501 y7&lt;-652 y8&lt;-719 y9&lt;-814 y10&lt;-110 List2&lt;-list(y1,y2,y3,y4,y5,y6,y7,y8,y9,y10) List2</pre><h2>Output</h2><pre class="result notranslate">[[1]] [1] 241 [[2]] [1] 215 [[3]] [1] 421 [[4]] [1] 295 [[5]] [1] 371 [[6]] [1] 501 [[7]] [1] 652 [[8]] [1] 719 [[9]] [1] 814 [[10]] [1] 110</pre><p>Decreasing the elements of List2 &minus;</p><h2>Example</h2><pre class="prettyprint notranslate">List2[order(unlist(List2),decreasing=TRUE)]</pre><h2>Output</h2><pre class="result notranslate">[[1]] [1] 814 [[2]] [1] 719 [[3]] [1] 652 [[4]] [1] 501 [[5]] [1] 421 [[6]] [1] 371 [[7]] [1] 295 [[8]] [1] 241 [[9]] [1] 215 [[10]] [1] 110</pre>
raja
Updated on 17-Oct-2020 09:00:48

Advertisements