Extract the Submatrix with Column Values Greater than 7 in R
Write a R program to extract the submatrix whose rows have column value > 7 from a given matrix.
Sample Solution:
R Programming Code:
# Define row names for the matrix
row_names = c("row1", "row2", "row3", "row4")
# Define column names for the matrix
col_names = c("col1", "col2", "col3", "col4")
# Create a 4x4 matrix with values from 1 to 16, row-wise, and assign row and column names
M = matrix(c(1:16), nrow = 4, byrow = TRUE, dimnames = list(row_names, col_names))
# Print the original matrix
print("Original Matrix:")
print(M)
# Extract the submatrix where the values in the 3rd column are greater than 7
result = M[M[,3] > 7,]
# Print the new submatrix
print("New submatrix:")
print(result)
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] "New submatrix:" col1 col2 col3 col4 row3 9 10 11 12 row4 13 14 15 16
Explanation:
- Define Row Names:
- row_names = c("row1", "row2", "row3", "row4")
- Creates a vector of row names for the matrix.
- Define Column Names:
- col_names = c("col1", "col2", "col3", "col4")
- Creates a vector of column names for the matrix.
- Create the Matrix:
- M = matrix(c(1:16), nrow = 4, byrow = TRUE, dimnames = list(row_names, col_names))
- Creates a 4x4 matrix with values from 1 to 16.
- nrow = 4 specifies 4 rows.
- byrow = TRUE fills the matrix row-wise.
- dimnames = list(row_names, col_names) assigns row and column names.
- Print the Original Matrix:
- print("Original Matrix:")
- print(M)
- Displays the original matrix with assigned row and column names.
- Extract Submatrix:
- result = M[M[,3] > 7,]
- Filters rows where the value in the 3rd column (M[,3]) is greater than 7.
- M[,3] > 7 creates a logical vector used for subsetting rows.
- Print the New Submatrix:
- print("New submatrix:")
- print(result)
- Displays the extracted submatrix where the 3rd column values are greater than 7.
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 matrix from a list of given vectors.
Next: Write a R program to convert a matrix to a 1 dimensional array.
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