📘 Premium Read: Access my best content on Medium member-only articles — deep dives into Java, Spring Boot, Microservices, backend architecture, interview preparation, career advice, and industry-standard best practices.
🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (176K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
1. Introduction
In R, vectors are fundamental data structures that store an ordered collection of items, which can be numbers, strings, or any other type. Finding the sum of vector elements is a common task. R provides a built-in function to achieve this, but for educational purposes, we'll also create a custom function.
2. Program Overview
1. We will use the built-in sum() function in R to get the sum of vector elements.
2. We will also create our own function named calculate_sum() to manually compute the sum.
3. Code Program
# Using built-in function to find the sum
sample_vector <- c(10, 20, 30, 40, 50)
built_in_sum <- sum(sample_vector)
print(paste("Sum using built-in function:", built_in_sum))
# Creating a custom function to compute the sum of vector elements
calculate_sum <- function(vec) {
total <- 0
for (value in vec) {
total <- total + value
}
return(total)
}
# Using custom function to find the sum
custom_sum <- calculate_sum(sample_vector)
print(paste("Sum using custom function:", custom_sum))
Output:
[1] "Sum using built-in function: 150" [1] "Sum using custom function: 150"
4. Step By Step Explanation
- We start by creating a sample vector named "sample_vector" with five elements.
- Using R's built-in sum() function, we quickly find the sum of the elements.
- To illustrate manual computation, we then create a function called calculate_sum(). This function initializes a variable "total" to zero and then iteratively adds each element of the vector to "total".
- Finally, we use the custom function on our sample vector and print out the results.
Both methods give the same outcome, confirming the accuracy of our custom function.
Comments
Post a Comment
Leave Comment