R Program to Find Sum of Vector Elements

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