w3resource

R Programming: Add Two Vectors of Integers Type and length 3


Write a R program to add two vectors of integers type and length 3.

Sample Solution :

R Programming Code :

# Create a vector 'x' of integer type and length 3
x = c(10, 20, 30)

# Create another vector 'y' of integer type and length 3
y = c(20, 10, 40)

# Print message indicating the original vectors
print("Original Vectors:")

# Print the contents of vector 'x'
print(x)

# Print the contents of vector 'y'
print(y)

# Print message indicating the result after adding the vectors
print("After adding two Vectors:")

# Add vectors 'x' and 'y' element-wise and store in 'z'
z = x + y

# Print the resulting vector 'z'
print(z)

Output:

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

Explanation:

  • Create vector x: Initializes a numeric vector x with three integer elements: 10, 20, 30.
  • Create vector y: Initializes another numeric vector y with three integer elements: 20, 10, 40.
  • Print message for original vectors: Displays the message "Original Vectors:" to indicate that the original vectors will be printed next.
  • Print vector x: Outputs the contents of vector x, which are 10, 20, 30.
  • Print vector y: Outputs the contents of vector y, which are 20, 10, 40.
  • Print message for result: Displays the message "After adding two Vectors:" to indicate that the result of the addition will be printed next.
  • Add vectors x and y: Performs an element-wise addition of vectors x and y and stores the result in a new vector z.
  • Print result vector z: Outputs the resulting vector z, which contains the sum of corresponding elements from vectors x and y, resulting in 30, 30, 70.

R Programming Code Editor:



Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a R program to create a vector of a specified type and length. Create vector of numeric, complex, logical and character types of length 6.
Next: Write a R program to append value to a given empty vector.

Test your Programming skills with w3resource's quiz.

What is the difficulty level of this exercise?



Follow us on Facebook and Twitter for latest update.