Introduction
Sorting is a fundamental operation in data manipulation and analysis. In R, you can easily sort vectors in ascending or descending order using built-in functions. This guide will walk you through writing an R program that sorts a vector and displays the sorted vector.
Problem Statement
Create an R program that:
- Creates a vector with a sequence of elements.
- Sorts the vector in ascending order.
- Sorts the vector in descending order.
- Displays the sorted vectors.
Example:
- Input: A vector with elements
c(5, 2, 8, 3, 1) - Output: Sorted vectors in ascending and descending order.
Solution Steps
- Create a Vector: Use the
c()function to create a vector with a sequence of elements. - Sort the Vector in Ascending Order: Use the
sort()function to sort the vector in ascending order. - Sort the Vector in Descending Order: Use the
sort()function with thedecreasingparameter set toTRUEto sort the vector in descending order. - Display the Sorted Vectors: Use the
print()function to display the sorted vectors.
R Program
# R Program to Sort a Vector
# Author: https://www.javaguides.net/
# Step 1: Create a vector with a sequence of elements
my_vector <- c(5, 2, 8, 3, 1)
# Step 2: Sort the vector in ascending order
sorted_ascending <- sort(my_vector)
# Step 3: Sort the vector in descending order
sorted_descending <- sort(my_vector, decreasing = TRUE)
# Step 4: Display the sorted vectors
print(paste("Sorted vector in ascending order:", paste(sorted_ascending, collapse = ", ")))
print(paste("Sorted vector in descending order:", paste(sorted_descending, collapse = ", ")))
Explanation
Step 1: Create a Vector
- The
c()function is used to create a vector with the elementsc(5, 2, 8, 3, 1).
Step 2: Sort the Vector in Ascending Order
- The
sort()function sorts the vector in ascending order by default and stores the result insorted_ascending.
Step 3: Sort the Vector in Descending Order
- The
sort()function is called again with thedecreasingparameter set toTRUEto sort the vector in descending order. The result is stored insorted_descending.
Step 4: Display the Sorted Vectors
- The
print()function is used to display the sorted vectors. Thepaste()function is used to concatenate the vector elements into a comma-separated string for display.
Output Example
Example:
[1] "Sorted vector in ascending order: 1, 2, 3, 5, 8"
[1] "Sorted vector in descending order: 8, 5, 3, 2, 1"
Conclusion
This R program demonstrates how to sort a vector in both ascending and descending order. It covers basic operations such as sorting and displaying vectors, making it a useful example for beginners learning R programming. Sorting is a common operation in data analysis, and understanding how to implement it in R is essential for effective data manipulation.