sort() Function in detail
In R, the sort() function is used to arrange the elements of a vector in either ascending or descending order. It returns a sorted version of the input vector and can also handle missing values (NA).
Syntax:
sort(x, decreasing, na.last)
Parameters:
- x: The vector to be sorted.
- decreasing: A Boolean value (
TRUEorFALSE). IfTRUE, sorts the vector in descending order. - na.last: A Boolean value. If
TRUE, places NA values at the end; ifFALSE, places them at the beginning.
Example 1: Sorting Numeric Vectors
# Creating a numeric vector
numbers <- c(10, -3, 5, 7, 2, NA, -8, 15)
# Sort in ascending order
sorted_numbers <- sort(numbers)
print(sorted_numbers)
Output:
[1] -8 -3 2 5 7 10 15
Example 2: Sorting with Descending Order and NA Handling
# Creating a numeric vector
values <- c(20, -7, 4, NA, 0, 12, -15)
# Sort in descending order
sorted_desc <- sort(values, decreasing = TRUE)
print(sorted_desc)
# Sort with NA values at the end
sorted_na_last <- sort(values, na.last = TRUE)
print(sorted_na_last)
Output:
[1] 20 12 4 0 -7 -15
[1] -15 -7 0 4 12 20 NA
Example 3: Sorting Character Vectors
# Creating a character vector
cities <- c("Delhi", "Mumbai", "Chennai", "Kolkata")
# Sort alphabetically
sorted_cities <- sort(cities)
print(sorted_cities)
Output:
[1] "Chennai" "Delhi" "Kolkata" "Mumbai"
Leave a Reply