Introduction
Finding the maximum and minimum elements in a vector is a common task in data analysis. In R, you can easily identify these elements using built-in functions. This guide will walk you through writing an R program to find and display the maximum and minimum elements in a vector.
Problem Statement
Create an R program that:
- Creates a vector with a sequence of elements.
- Finds the maximum element in the vector.
- Finds the minimum element in the vector.
- Displays the maximum and minimum elements.
Example:
- Input: A vector with elements
c(10, 25, 3, 47, 15) - Output: Maximum element:
47, Minimum element:3
Solution Steps
- Create a Vector: Use the
c()function to create a vector with a sequence of elements. - Find the Maximum Element: Use the
max()function to find the maximum element in the vector. - Find the Minimum Element: Use the
min()function to find the minimum element in the vector. - Display the Maximum and Minimum Elements: Use the
print()function to display the maximum and minimum elements.
R Program
# R Program to Find the Maximum and Minimum Elements in a Vector
# Author: https://www.javaguides.net/
# Step 1: Create a vector with a sequence of elements
my_vector <- c(10, 25, 3, 47, 15)
# Step 2: Find the maximum element in the vector
max_element <- max(my_vector)
# Step 3: Find the minimum element in the vector
min_element <- min(my_vector)
# Step 4: Display the maximum and minimum elements
print(paste("Maximum element:", max_element))
print(paste("Minimum element:", min_element))
Explanation
Step 1: Create a Vector
- The
c()function is used to create a vector with the elementsc(10, 25, 3, 47, 15).
Step 2: Find the Maximum Element
- The
max()function is used to find the maximum element in the vector. The result is stored inmax_element.
Step 3: Find the Minimum Element
- The
min()function is used to find the minimum element in the vector. The result is stored inmin_element.
Step 4: Display the Maximum and Minimum Elements
- The
print()function is used to display the maximum and minimum elements with descriptive messages.
Output Example
Example:
[1] "Maximum element: 47"
[1] "Minimum element: 3"
Conclusion
This R program demonstrates how to find the maximum and minimum elements in a vector using the max() and min() functions. It covers basic operations such as vector creation, finding extreme values, and displaying results, making it a valuable example for beginners learning R programming. Understanding how to identify these values is crucial for data analysis and manipulation.