w3resource

Combine three Vectors into a 3×3 Matrix in R Programming

R Programming: Basic Exercise-12 with Solution

Write a R program to create three vectors a,b,c with 3 integers. Combine the three vectors to become a 3×3 matrix where each column represents a vector. Print the content of the matrix.

Sample Solution :

R Programming Code :

# Create a vector 'a' with values 1, 2, and 3
a <- c(1, 2, 3)

# Create a vector 'b' with values 4, 5, and 6
b <- c(4, 5, 6)

# Create a vector 'c' with values 7, 8, and 9
c <- c(7, 8, 9)

# Combine vectors 'a', 'b', and 'c' into a matrix by columns
m <- cbind(a, b, c)

# Print a message indicating that the following output is the content of the matrix
print("Content of the said matrix:")

# Print the matrix 'm'
print(m)

Output:

[1] "Content of the said matrix:"
     a b c
[1,] 1 4 7
[2,] 2 5 8
[3,] 3 6 9                         

Explanation:

  • Create three vectors:
    • a <- c(1, 2, 3) creates a vector a containing the values 1, 2, 3.
    • b <- c(4, 5, 6) creates a vector b containing the values 4, 5, 6.
    • c <- c(7, 8, 9) creates a vector c containing the values 7, 8, 9.
  • Combine vectors into a matrix:
    • m <- cbind(a, b, c) combines the three vectors a, b, and c column-wise to form a 3×3 matrix m.
    • Print the matrix:
    • print("Content of the said matrix:") prints a label indicating the matrix content.
    • print(m) prints the matrix m showing each vector as a column.

R Programming Code Editor:



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

Previous: Write a R program to get the unique elements of a given string and unique numbers of vector.
Next: Write a R program to create a list of random numbers in normal distribution and count occurrences of each value.

Test your Programming skills with w3resource's quiz.

What is the difficulty level of this exercise?



Become a Patron!

Follow us on Facebook and Twitter for latest update.

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/basic/r-programming-basic-exercise-12.php