DS Ex2
DS Ex2
NO:2
Functions in R
DATE:
AIM:
To study about functions in R and implement them.
PROCEDURE:
Step 1: Input Validation: Ensure the input is a single positive numeric value.
Step 2 : Base Case: If the number is less than 10, return the number itself.
Step 3 : Recursive Case: Add the last digit (number %% 10) to the sum of the
remaining digits (floor(number / 10)).
Step 4 : Recursive Call: Repeat until the base case is reached, then return the
accumulated sum.
Step 5 :redict Sales: Validate inputs, compute the average of historical sales, calculate
the predicted sales using the growth rate, and return the result.
Step 6 : Bonus Calculator: Validate the base salary, define a nested function to
calculate bonuses based on performance ratings using percentages, and return the nested
function.
Step 7 : Sum of Digits: Validate the input, define a base case for single-digit numbers,
recursively compute the sum of digits by separating and adding the last digit, and return the
final sum.
SOURCE CODE:
1.
predict_sales <- function(sales_data, growth_rate) {
if (!is.numeric(sales_data)) {
stop("The sales_data argument must be a numeric vector.")
}
if (!is.numeric(growth_rate) || length(growth_rate) != 1) {
stop("The growth_rate argument must be a single numeric value representing a
percentage.")
}
average_sales <- mean(sales_data, na.rm = TRUE)
growth_factor <- growth_rate / 100
predicted_sales <- average_sales * (1 + growth_factor)
return(predicted_sales)
}
sales_data <- c(5000, 5500, 6000, 6500, 7000)
growth_rate <- 10
predicted_sales <- predict_sales(sales_data, growth_rate)
cat("Predicted sales for the next year:", predicted_sales, "\n")
2.
SOURCE CODE:
3.
SOURCE CODE:
sum_of_digits <- function(number) {
if (!is.numeric(number) || length(number) != 1 || number < 0) {
stop("Input must be a single positive numeric value.")
}
if (number < 10) {
return(number)
}
return((number %% 10) + sum_of_digits(floor(number / 10)))
}
number <- 1234
result <- sum_of_digits(number)
cat("The sum of the digits of", number, "is:", result, "\n")
RESULT:
Thus functions in R are studied and executed successfully.