Open In App

Sum of Vector Elements using a for Loop

Last Updated : 01 Nov, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

R is a powerful programming language and surroundings used for facts analysis, statistical computing, and statistics visualization. One common assignment in facts analysis is calculating the sum of factors in a vector. A vector is a fundamental information structure in R Programming Language that shops a collection of values of the equal facts type. we might need to calculate the sum of factors in a vector for diverse reasons, such as finding the whole sales of a product, calculating the common rating of college students, or summarizing records for similar evaluation.

Concepts Related to the Topic

Before diving into the practical implementation, it’s crucial to recognize some key principles associated with vectors and for loops in R.

Vectors in R

  1. A vector in R is a one-dimensional array that can hold factors of identical statistics kind.
  2. These elements may be numeric, personal, logical, or different information kinds.
  3. You can create vectors using the c() characteristic or by specifying sequences with the usage of features like seq() and rep(). For instance.

R




# Creating a numeric vector
numbers <- c(1, 2, 3, 4, 5)
print(numbers)
# Creating a character vector
fruits <- c("apple", "banana", "cherry")
print(fruits)
# Creating a sequence of numbers
sequence <- seq(1, 10, by = 2)
print(sequence)


Output:

[1] 1 2 3 4 5
[1] "apple" "banana" "cherry"
[1] 1 3 5 7 9

For Loops in R

A for loop is a control glide assertion in R that permits you to again and again execute a block of code for a distinct wide variety of times or over a series of values.

The primary syntax of a for loop in R is as follows.

for (variable in sequence) {
# Code to be executed for each value of 'variable'
}

Create a Vector

First, you need to create a vector containing the elements for that you need to calculate the sum.

You can create vectors as discussed earlier the use of the c() function or other appropriate strategies.

R




# Create a numeric vector
numbers <- c(1, 2, 3, 4, 5)


Initialise a Sum Variable

Next, you ought to initialise a variable to shop the sum of the vector elements.

This variable might be updated inside the for loop as you iterate through the vector.

R




# Initialize a sum variable
total_sum <- 0


Use a For Loop to Iterate over vector and Calculate the Sum

Now, you may use a for loop to iterate via the vector and collect the values in the sum variable.

Here’s a easy for loop that calculates the sum of elements within the numbers vector:

R




# Use a for loop to calculate the sum
for (num in numbers) {
  total_sum <- total_sum + num
}


Display the Result

Finally, you may display the calculated sum using the cat() feature or another manner.

R




# Display the result
cat("The sum of elements in the vector is:", total_sum, "\n")


Output:

The sum of elements in the vector is: 15 

Example 1: Sum of Numeric Elements

Suppose you have a vector scores representing the test rankings of college students, and also you want to calculate the entire rating. Here’s how you may do it:

R




# Create a numeric vector of test scores
scores <- c(85, 92, 78, 95, 88)
 
# Initialize a sum variable
total_score <- 0
 
# Use a for loop to calculate the sum
for (score in scores) {
  total_score <- total_score + score
}
 
# Display the result
cat("The total test score is:", total_score, "\n")


Output:

The total test score is: 438 

In this example, the for loop iterates through the scores vector, including each score to the total_score variable. The final result is displayed using the cat() feature.

Example 2: Sum of Even Numbers

Suppose we got a vector numbers containing a chain of numbers, and also you need to calculate the sum of even numbers inside that vector:

R




# Create a vector of numbers
numbers <- 1:10
 
# Initialize a sum variable
even_sum <- 0
 
# Use a for loop to calculate the sum of even numbers
for (num in numbers) {
  if (num %% 2 == 0) {  # Check if the number is even
    even_sum <- even_sum + num
  }
}
 
# Display the result
cat("The sum of even numbers in the vector is:", even_sum)


Output:

The sum of even numbers in the vector is: 30

In this example, we use an if statement inside the for loop to test if each variety is even (divisible by using 2) before adding it to the even_sum variable.

Example 3: Sum of Elements in a Vector of Prices

Suppose we got a vector expenses representing the fees of numerous merchandise, and you need to calculate the whole value of buying all the goods.

R




# Create a vector of product prices
prices <- c(19.99, 29.95, 12.49, 49.99, 9.99)
 
# Initialize a sum variable
total_cost <- 0
 
# Use a for loop to calculate the total cost
for (price in prices) {
  total_cost <- total_cost + price
}
 
# Display the result
cat("The total cost of purchasing all products is:", total_cost, "\n")


Output:

The total cost of purchasing all products is: 122.41 

In this case, the for loop iterates thru the costs vector and accumulates the costs within the total_cost variable to locate the full value of buying all the goods.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads