The purpose of this R program is to calculate several cumulative properties for a given numeric vector:
- Cumulative Sum: The running total of elements.
- Cumulative Product: The running product of elements.
- Cumulative Minimum: The smallest element encountered at each step.
- Cumulative Maximum: The largest element encountered at each step.
Program :
# Define a function to calculate cumulative sums
cumulative_sum <- function(vec) {
return(cumsum(vec))
}
# Define a function to calculate cumulative products
cumulative_product <- function(vec) {
return(cumprod(vec))
}
# Define a function to calculate cumulative minima
cumulative_minimum <- function(vec) {
return(cummin(vec))
}
# Define a function to calculate cumulative maxima
cumulative_maximum <- function(vec) {
return(cummax(vec))
}
# Main function to calculate all cumulative values
calculate_cumulative <- function(vec) {
if (!is.numeric(vec)) {
stop("Input vector must be numeric.")
}
cat("Input Vector: ", vec, "\n\n")
cat("Cumulative Sum: ", cumulative_sum(vec), "\n")
cat("Cumulative Product: ", cumulative_product(vec), "\n")
cat("Cumulative Minimum: ", cumulative_minimum(vec), "\n")
cat("Cumulative Maximum: ", cumulative_maximum(vec), "\n")
}
# Test the program with a sample vector
sample_vector <- c(5, 2, -3, 10, 4)
calculate_cumulative(sample_vector)
Output :
Input Vector: 5 2 -3 10 4
Cumulative Sum: 5 7 4 14 18
Cumulative Product: 5 10 -30 -300 -1200
Cumulative Minimum: 5 2 -3 -3 -3
Cumulative Maximum: 5 5 5 10 10
No comments:
Post a Comment