Sum of Vector Elements using a for Loop
Last Updated :
01 Nov, 2023
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
- A vector in R is a one-dimensional array that can hold factors of identical statistics kind.
- These elements may be numeric, personal, logical, or different information kinds.
- You can create vectors using the c() characteristic or by specifying sequences with the usage of features like seq() and rep(). For instance.
R
numbers <- c (1, 2, 3, 4, 5)
print (numbers)
fruits <- c ( "apple" , "banana" , "cherry" )
print (fruits)
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
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.
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
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
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
scores <- c (85, 92, 78, 95, 88)
total_score <- 0
for (score in scores) {
total_score <- total_score + score
}
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
numbers <- 1:10
even_sum <- 0
for (num in numbers) {
if (num %% 2 == 0) {
even_sum <- even_sum + num
}
}
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
prices <- c (19.99, 29.95, 12.49, 49.99, 9.99)
total_cost <- 0
for (price in prices) {
total_cost <- total_cost + price
}
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.
Share your thoughts in the comments
Please Login to comment...