R Program to add two vectors

How to add two vectors

Here we are explaining how to write an R program to find the sum of two vectors. We can give two vector values to calculate the sum. For the calculation of vector sum here we use the plus(+) operator.

How two vectors are added using the R Program

Given below are the steps which are used in the R program to find the sum of two vectors. In this R program, we accept the vector values into variables A and B. The sum of vectors is assigned variable C.Finally the variable C is printed as output vector.

ALGORITHM

  • STEP 1 : take the two vector values into the variables A, B
  • STEP 2 : Consider C as the sum vector
  • STEP 3 : Calculate the vector sum using the + operator
  • STEP 4 : First print the original vectors
  • STEP 5 : Assign the sum to vector C as C = A + B
  • STEP 6 : print the vector C as result vector

R Source Code

# Input vectors
A = c(30, 20, 10)
B = c(10, 10, 30)

print("Original Vectors:")
## [1] "Original Vectors:"
print(A); print(B);
## [1] 30 20 10
## [1] 10 10 30
print("After adding two Vectors:")
## [1] "After adding two Vectors:"
C = A + B
print(C)
## [1] 40 30 40

R Source Code

# Input vectors
A = c(45, 55, 15)
B = c(25, 35, 25)

print("Original Vectors:")
## [1] "Original Vectors:"
print(A); print(B);
## [1] 45 55 15
## [1] 25 35 25
print("After adding two Vectors:")
## [1] "After adding two Vectors:"
C = A + B
print(C)
## [1] 70 90 40