Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • GfG 160: Daily DSA
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Sorting of Arrays in R Programming
Next article icon

Sorting of Arrays in R Programming

Last Updated : 12 Jul, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

Prerequisite: R – Array

A vector is a uni-dimensional array, which is specified by a single dimension, length. A Vector can be created using the ‘c()‘ function. A list of values is passed to the c() function to create a vector. Sorting can be done either in ascending order or descending. There are few things which should be kept in mind before sorting. They are as follows:

  • Order in which sorting needs to be performed - Ascending/Descending.
  • Sorting according to multiple column criteria.
  • Handling missing and duplicate values during sorting. The analyst must decide what should be done with missing and duplicate values. The overall impact on the data should be considered before removing or replacing null values.

Method 1: sort() function

sort() function in R is used to sort a vector. By default, it sorts a vector in increasing order. To sort in descending order, add a "decreasing" parameter to the sort function.

Syntax:

sort(name_of_vector, decreasing = TRUE)

Parameters:

name_of_vector: Vector to be sorted

decreasing: Boolean value to sort in descending order

Example 1:

R
# create a linear array
arr <- c(9, 8, 7, 6, 5, 4, 3, 2, 1)

# use of sort function to sort array 
# by default it is sorted in increasing order
sort(arr)

  

Output:


 

[1] 1 2 3 4 5 6 7 8 9


 

Example 2:


 

R
# create linear array 
arr <- c(1, 2, 3, 4, 5, 6, 7, 8, 9)

# use in built sort function 
# to sort in decreasing order
sort(arr, decreasing = TRUE)

  

Output:


 

[1] 9 8 7 6 5 4 3 2 1

Note: The major drawback of the sort() function is that it cannot sort data frames.

Method 2: order() function


 

To overcome the drawback in method 1, we use the order() function, which also sorts data frames according to the specified column. To sort in decreasing order add negative sign. Data can also be sorted with multiple criteria. Suppose if the age of two persons is the same then, we can sort them on the basis of their names i.e. lexicographically. See the below examples.


 

Example 1:


 

R
# define dataframe
df <- data.frame("Age" = c(12, 21, 15, 5, 25),
                 "Name" = c("Johnny", "Glen", "Alfie",
                            "Jack", "Finch"))

# sort the dataframe on the basis of
# age column and store it in newdf
newdf <- df[order(df$Age), ]

# print sorted dataframe
print(newdf)

  

Output:


 

   Age  Name
4  5    Jack
1  12   Johnny
3  15   Alfie
2  21   Glen
5  25   Finch


 

Example 2:


 

R
# define vector
r = c(10, 20, 30, 40, 50, 60)

# sort in decreasing order
order(-r)

  

Output:


 

[1] 6 5 4 3 2 1


 

Example 3:


 

R
# define dataframe
df <- data.frame("Age" = c(12, 21, 15, 12, 25, 12),
                 "Name" = c("Johnny", "Glen", "Alfie",
                            "Jack", "Finch", "Aaron"))

# sort the dataframe first on the basis of
# Age and if age is same perform sort on Name
newdf <- df[order(df$Age, df$Name), ]

# print sorted dataframe
print(newdf)

  

Output:


 

  Age   Name
6  12   Aaron
4  12   Jack
1  12   Johnny
3  15   Alfie
2  21   Glen
5  25   Finch

Note: The output above is the indices of numbers. For instance, 60 is the largest in vector and had index 6. Thus, 6 is displayed first. 

Method 3: Sorting array using the loop

  • Create a linear array, say arr
  • Create a variable swap. If swap is false after traversing the entire array, it means the array is already sorted and break the loop
  • Else, run loop and copy original array into another array, say newArr, and start comparing adjacent elements in the original array
  • If the current element is smaller than the previous element, then copy the current element of arr into the previous position of newArr and the previous element of arr into the current position of newArr. The newArr now has swapped elements.
  • Copy newArr to original array arr and make swap = TRUE.
  • Repeat until arr is sorted


 

Below is the implementation of the above approach.


 

R
# create linear array
arr <- c(9, 4, 5, 4, 5, 6, 3, 2, 1)

# repeat until break is encountered
repeat 
{
      # create a variable swap
    swap = FALSE
  
      # run loop from 2nd element till last element
    for (i in 2:length(arr)) 
    {
          # copy original array into newArr
        newArr <- arr
        if (arr[i - 1] > arr[i]) 
        {
            newArr[i - 1] <- arr[i]
            newArr[i] <- arr[i - 1]
            arr <- newArr
            swapped <- TRUE
        }
    }
    if (!swapped) {break}
}
print(arr)

  

Output:


 

[1] 1 2 3 4 4 5 5 6 9

Method 4: The use of dplyr package


 

dplyr package is easy to use and reliable. The package includes arrange() method to sort the data. See the below examples.


 

Example 1:


 

R
# install package dplyr
install.packages("dplyr")

# import library dplyr
library(dplyr)

# create dataframe
df <- data.frame("Age" = c(12, 21, 15, 5, 25), 
                 "Name" = c("Johnny", "Glen", "Alfie", 
                            "Jack", "Finch"))

# sort the dataframe on the basis of
# age column using arrange method
arrange(df,age)

  

Output:


 

   Age  Name
4  5    Jack
1  12   Johnny
3  15   Alfie
2  21   Glen
5  25   Finch


 


Next Article
Sorting of Arrays in R Programming

R

rohanchopra96
Improve
Article Tags :
  • Python
  • R Language
  • R-Arrays
Practice Tags :
  • python

Similar Reads

  • Types of Sorting Algorithm in R Programming
    There are multiple ways by which data can be sorted in the R language. It’s up to the data Analyst to consider the most suitable method based upon the structure of the data. There are multiple algorithms for performing sorting on the data in the R programming language. Below different types of sorti
    6 min read
  • Array vs Matrix in R Programming
    The data structure is a particular way of organizing data in a computer so that it can be used effectively. The idea is to reduce the space and time complexities of different tasks. Data structures in R programming are tools for holding multiple values. The two most important data structures in R ar
    3 min read
  • Array Operations in R Programming
    Arrays are the R data objects which store the data in more than two dimensions. Arrays are n-dimensional data structures. For example, if we create an array of dimensions (2, 3, 3) then it creates 3 rectangular matrices each with 2 rows and 3 columns. They are homogeneous data structures. Now, let’s
    4 min read
  • Basic Syntax in R Programming
    R is the most popular language used for Statistical Computing and Data Analysis with the support of over 10, 000+ free packages in CRAN repository. Like any other programming language, R has a specific syntax which is important to understand if you want to make use of its features. This article assu
    3 min read
  • Sorting of a Vector in R Programming - sort() Function
    In R Programming Language we can sort a vector in ascending or descending order using the sort() function. The sort() function returns a sorted version of the input vector. sort() function in is used to sort a vector by its values. It takes the Boolean value as an argument to sort in ascending or de
    2 min read
  • R Programming for Data Science
    R is an open-source programming language used statistical software and data analysis tools. It is an important tool for Data Science. It is highly popular and is the first choice of many statisticians and data scientists.R includes powerful tools for creating aesthetic and insightful visualizations.
    13 min read
  • Reordering of a Data Set in R Programming - arrange() Function
    arrange() function in R Language is used for reordering of table rows with the help of column names as expression passed to the function. Syntax: arrange(x, expr) Parameters: x: data set to be reordered expr: logical expression with column name Example 1: Python3 1== # R program to reorder a data se
    1 min read
  • Assigning Vectors in R Programming
    Vectors are one of the most basic data structure in R. They contain data of same type. Vectors in R is equivalent to arrays in other programming languages. In R, array is a vector of one or more dimensions and every single object created is stored in the form of a vector. The members of a vector are
    5 min read
  • How to Code in R programming?
    R is a powerful programming language and environment for statistical computing and graphics. Whether you're a data scientist, statistician, researcher, or enthusiast, learning R programming opens up a world of possibilities for data analysis, visualization, and modeling. This comprehensive guide aim
    4 min read
  • Level Ordering of Factors in R Programming
    Level ordering controls how categorical values are stored, displayed, and interpreted in analyses and plots. By default, R orders factor levels alphabetically. In this article, we will see the level ordering of factors in the R Programming Language.What Are Factors in R?Factors are data objects used
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

'); // $('.spinner-loading-overlay').show(); let script = document.createElement('script'); script.src = 'https://assets.geeksforgeeks.org/v2/editor-prod/static/js/bundle.min.js'; script.defer = true document.head.appendChild(script); script.onload = function() { suggestionModalEditor() //to add editor in suggestion modal if(loginData && loginData.premiumConsent){ personalNoteEditor() //to load editor in personal note } } script.onerror = function() { if($('.editorError').length){ $('.editorError').remove(); } var messageDiv = $('
').text('Editor not loaded due to some issues'); $('#suggestion-section-textarea').append(messageDiv); $('.suggest-bottom-btn').hide(); $('.suggestion-section').hide(); editorLoaded = false; } }); //suggestion modal editor function suggestionModalEditor(){ // editor params const params = { data: undefined, plugins: ["BOLD", "ITALIC", "UNDERLINE", "PREBLOCK"], } // loading editor try { suggestEditorInstance = new GFGEditorWrapper("suggestion-section-textarea", params, { appNode: true }) suggestEditorInstance._createEditor("") $('.spinner-loading-overlay:eq(0)').remove(); editorLoaded = true; } catch (error) { $('.spinner-loading-overlay:eq(0)').remove(); editorLoaded = false; } } //personal note editor function personalNoteEditor(){ // editor params const params = { data: undefined, plugins: ["UNDO", "REDO", "BOLD", "ITALIC", "NUMBERED_LIST", "BULLET_LIST", "TEXTALIGNMENTDROPDOWN"], placeholderText: "Description to be......", } // loading editor try { let notesEditorInstance = new GFGEditorWrapper("pn-editor", params, { appNode: true }) notesEditorInstance._createEditor(loginData&&loginData.user_personal_note?loginData.user_personal_note:"") $('.spinner-loading-overlay:eq(0)').remove(); editorLoaded = true; } catch (error) { $('.spinner-loading-overlay:eq(0)').remove(); editorLoaded = false; } } var lockedCasesHtml = `You can suggest the changes for now and it will be under 'My Suggestions' Tab on Write.

You will be notified via email once the article is available for improvement. Thank you for your valuable feedback!`; var badgesRequiredHtml = `It seems that you do not meet the eligibility criteria to create improvements for this article, as only users who have earned specific badges are permitted to do so.

However, you can still create improvements through the Pick for Improvement section.`; jQuery('.improve-header-sec-child').on('click', function(){ jQuery('.improve-modal--overlay').hide(); $('.improve-modal--suggestion').hide(); jQuery('#suggestion-modal-alert').hide(); }); $('.suggest-change_wrapper, .locked-status--impove-modal .improve-bottom-btn').on('click',function(){ // when suggest changes option is clicked $('.ContentEditable__root').text(""); $('.suggest-bottom-btn').html("Suggest changes"); $('.thank-you-message').css("display","none"); $('.improve-modal--improvement').hide(); $('.improve-modal--suggestion').show(); $('#suggestion-section-textarea').show(); jQuery('#suggestion-modal-alert').hide(); if(suggestEditorInstance !== null){ suggestEditorInstance.setEditorValue(""); } $('.suggestion-section').css('display', 'block'); jQuery('.suggest-bottom-btn').css("display","block"); }); $('.create-improvement_wrapper').on('click',function(){ // when create improvement option clicked then improvement reason will be shown if(loginData && loginData.isLoggedIn) { $('body').append('
'); $('.spinner-loading-overlay').show(); jQuery.ajax({ url: writeApiUrl + 'create-improvement-post/?v=1', type: "POST", contentType: 'application/json; charset=utf-8', dataType: 'json', xhrFields: { withCredentials: true }, data: JSON.stringify({ gfg_id: post_id }), success:function(result) { $('.spinner-loading-overlay:eq(0)').remove(); $('.improve-modal--overlay').hide(); $('.unlocked-status--improve-modal-content').css("display","none"); $('.create-improvement-redirection-to-write').attr('href',writeUrl + 'improve-post/' + `${result.id}` + '/', '_blank'); $('.create-improvement-redirection-to-write')[0].click(); }, error:function(e) { showErrorMessage(e.responseJSON,e.status) }, }); } else { if(loginData && !loginData.isLoggedIn) { $('.improve-modal--overlay').hide(); if ($('.header-main__wrapper').find('.header-main__signup.login-modal-btn').length) { $('.header-main__wrapper').find('.header-main__signup.login-modal-btn').click(); } return; } } }); $('.left-arrow-icon_wrapper').on('click',function(){ if($('.improve-modal--suggestion').is(":visible")) $('.improve-modal--suggestion').hide(); else{ } $('.improve-modal--improvement').show(); }); const showErrorMessage = (result,statusCode) => { if(!result) return; $('.spinner-loading-overlay:eq(0)').remove(); if(statusCode == 403) { $('.improve-modal--improve-content.error-message').html(result.message); jQuery('.improve-modal--overlay').show(); jQuery('.improve-modal--improvement').show(); $('.locked-status--impove-modal').css("display","block"); $('.unlocked-status--improve-modal-content').css("display","none"); $('.improve-modal--improvement').attr("status","locked"); return; } } function suggestionCall() { var editorValue = suggestEditorInstance.getValue(); var suggest_val = $(".ContentEditable__root").find("[data-lexical-text='true']").map(function() { return $(this).text().trim(); }).get().join(' '); suggest_val = suggest_val.replace(/\s+/g, ' ').trim(); var array_String= suggest_val.split(" ") //array of words var gCaptchaToken = $("#g-recaptcha-response-suggestion-form").val(); var error_msg = false; if(suggest_val != "" && array_String.length >=4){ if(editorValue.length { jQuery('.ContentEditable__root').focus(); jQuery('#suggestion-modal-alert').hide(); }, 3000); } } document.querySelector('.suggest-bottom-btn').addEventListener('click', function(){ jQuery('body').append('
'); jQuery('.spinner-loading-overlay').show(); if(loginData && loginData.isLoggedIn) { suggestionCall(); return; } // script for grecaptcha loaded in loginmodal.html and call function to set the token setGoogleRecaptcha(); }); $('.improvement-bottom-btn.create-improvement-btn').click(function() { //create improvement button is clicked $('body').append('
'); $('.spinner-loading-overlay').show(); // send this option via create-improvement-post api jQuery.ajax({ url: writeApiUrl + 'create-improvement-post/?v=1', type: "POST", contentType: 'application/json; charset=utf-8', dataType: 'json', xhrFields: { withCredentials: true }, data: JSON.stringify({ gfg_id: post_id }), success:function(result) { $('.spinner-loading-overlay:eq(0)').remove(); $('.improve-modal--overlay').hide(); $('.create-improvement-redirection-to-write').attr('href',writeUrl + 'improve-post/' + `${result.id}` + '/', '_blank'); $('.create-improvement-redirection-to-write')[0].click(); }, error:function(e) { showErrorMessage(e.responseJSON,e.status); }, }); });
"For an ad-free experience and exclusive features, subscribe to our Premium Plan!"
Continue without supporting
`; $('body').append(adBlockerModal); $('body').addClass('body-for-ad-blocker'); const modal = document.getElementById("adBlockerModal"); modal.style.display = "block"; } function handleAdBlockerClick(type){ if(type == 'disabled'){ window.location.reload(); } else if(type == 'info'){ document.getElementById("ad-blocker-div").style.display = "none"; document.getElementById("ad-blocker-info-div").style.display = "flex"; handleAdBlockerIconClick(0); } } var lastSelected= null; //Mapping of name and video URL with the index. const adBlockerVideoMap = [ ['Ad Block Plus','https://media.geeksforgeeks.org/auth-dashboard-uploads/abp-blocker-min.mp4'], ['Ad Block','https://media.geeksforgeeks.org/auth-dashboard-uploads/Ad-block-min.mp4'], ['uBlock Origin','https://media.geeksforgeeks.org/auth-dashboard-uploads/ub-blocke-min.mp4'], ['uBlock','https://media.geeksforgeeks.org/auth-dashboard-uploads/U-blocker-min.mp4'], ] function handleAdBlockerIconClick(currSelected){ const videocontainer = document.getElementById('ad-blocker-info-div-gif'); const videosource = document.getElementById('ad-blocker-info-div-gif-src'); if(lastSelected != null){ document.getElementById("ad-blocker-info-div-icons-"+lastSelected).style.backgroundColor = "white"; document.getElementById("ad-blocker-info-div-icons-"+lastSelected).style.borderColor = "#D6D6D6"; } document.getElementById("ad-blocker-info-div-icons-"+currSelected).style.backgroundColor = "#D9D9D9"; document.getElementById("ad-blocker-info-div-icons-"+currSelected).style.borderColor = "#848484"; document.getElementById('ad-blocker-info-div-name-span').innerHTML = adBlockerVideoMap[currSelected][0] videocontainer.pause(); videosource.setAttribute('src', adBlockerVideoMap[currSelected][1]); videocontainer.load(); videocontainer.play(); lastSelected = currSelected; }

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences