Sorting of a Vector in R Programming – sort() Function

sort() function in R Language is used to sort a vector by its values. It takes Boolean value as argument to sort in ascending or descending order.

Syntax:
sort(x, decreasing, na.last)

Parameters:
x: Vector to be sorted
decreasing: Boolean value to sort in descending order
na.last: Boolean value to put NA at the end

Example 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

# R program to sort a vector
  
# Creating a vector
x <- c(7, 4, 3, 9, 1.2, -4, -5, -8, 6, NA)
  
# Calling sort() function
sort(x)

chevron_right


Output:

[1] -8.0 -5.0 -4.0  1.2  3.0  4.0  6.0  7.0  9.0

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

# R program to sort a vector
  
# Creating a vector
x <- c(7, 4, 3, 9, 1.2, -4, -5, -8, 6, NA)
  
# Calling sort() function
# to print in decreasing order
sort(x, decreasing = TRUE)
  
# Calling sort() function
# to print NA at the end
sort(x, na.last = TRUE)

chevron_right


Output:

[1]  9.0  7.0  6.0  4.0  3.0  1.2 -4.0 -5.0 -8.0
[1] -8.0 -5.0 -4.0  1.2  3.0  4.0  6.0  7.0  9.0   NA
My Personal Notes arrow_drop_up

Recommended Posts:


Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.