R Programming: Convert a matrix to a 1 dimensional array
R Programming: Matrix Exercise-8 with Solution
Write a R program to convert a matrix to a 1 dimensional array.
Sample Solution:
R Programming Code:
row_names = c("row1", "row2", "row3", "row4")
col_names = c("col1", "col2", "col3", "col4")
M = matrix(c(1:16), nrow = 4, byrow = TRUE, dimnames = list(row_names, col_names))
print("Original Matrix:")
print(M)
result = as.vector(M)
print("1 dimensional array (column wise):")
print(result)
result = as.vector(t(M))
print("1 dimensional array (row wise):")
print(result)
Sample Output:
[1] "Original Matrix:" col1 col2 col3 col4 row1 1 2 3 4 row2 5 6 7 8 row3 9 10 11 12 row4 13 14 15 16 [1] "1 dimensional array (column wise):" [1] 1 5 9 13 2 6 10 14 3 7 11 15 4 8 12 16 [1] "1 dimensional array (row wise):" [1] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
R Programming Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Write a R program to extract the submatrix whose rows have column value > 7 from a given matrix.
Next: Write a R program to create a correlation matrix from a dataframe of same data type.
Test your Programming skills with w3resource's quiz.
What is the difficulty level of this exercise?
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics