R Programming: Multiply Two Vectors of integers in R
R Programming: Vector Exercise-4 with Solution
Write a R program to multiply two vectors of integers type and length 3.
Sample Solution :
R Programming Code :
# Define the first vector 'x' with integer values
x = c(10, 20, 30)
# Define the second vector 'y' with integer values
y = c(20, 10, 40)
# Print a message indicating the original vectors
print("Original Vectors:")
# Print the first vector 'x'
print(x)
# Print the second vector 'y'
print(y)
# Print a message indicating the product of the two vectors
print("Product of two Vectors:")
# Multiply the corresponding elements of vectors 'x' and 'y' and store in 'z'
z = x * y
# Print the result of the division
print(z)
Output:
[1] "Original Vectors:" [1] 10 20 30 [1] 20 10 40 [1] "Product of two Vectors:" [1] 200, 200, 1200
Explanation:
- Define Vectors:
- x = c(10, 20, 30): Creates a numeric vector x with three elements: 10, 20, and 30.
- y = c(20, 10, 40): Creates another numeric vector y with three elements: 20, 10, and 40.
- Print Original Vectors:
- print("Original Vectors:"): Prints the message "Original Vectors:" to the console.
- print(x): Prints the elements of vector x.
- print(y): Prints the elements of vector y.
- Print Product of Two Vectors:
- print("Product of two Vectors:"): Prints the message "Product of two Vectors:" to the console.
- Multiplying the Vectors:
- z = x * y multiplies the corresponding elements of vectors x and y element-wise. The multiplication happens as follows:
- 10 (from x) * 20 (from y) = 200
- 20 (from x) * 10 (from y) = 200
- 30 (from x) * 40 (from y) = 1200
- The result is stored in a new vector z, which will contain 200, 200, 1200.
- Print Result:
- print(z): Prints the resulting vector z, which contains the multiplication results: 200, 200, 1200.
R Programming Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Write a R program to append value to a given empty vector.
Next: Write a R program to divide two vectors of integers type and length 3.
Test your Programming skills with w3resource's quiz.
What is the difficulty level of this exercise?
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/r-programming-exercises/vector/r-programming-vector-exercise-4.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics