R Program to add two vectors


February 5, 2023, Learn eTutorial
1994

What are vectors in R?

We can define a vector as a data structure in R that can hold a sequence of elements that are of the same type. elements in the vector can be called components and finally, a vector can be to support integer, logical, character, double, and even raw datatypes.

How to add two vectors

To add two or more vector values in R  we are using the + operator and a variable to store the vector result.

How two vectors are added using the R Program?

In this R program, we accept the vector values into variables A and B from the user. The sum of vectors is assigned to variable C. then we calculate the sum using the + operator and variable C is printed as the 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 the result vector

 

R Source Code

                                          A = c(30, 20, 10)
B = c(10, 10, 30)
print("Original Vectors:")
print(A)
print(B)
print("After adding two Vectors:")
C = A + B
print(C)
                                      

OUTPUT

[1] "Original Vectors:"
[1] 30 20 10
[1] 10 10 30
[1] "After adding two Vectors:"
[1] 40 30 40