The “as.matrix” Function in R
Package: Base R (no specific package required)
Purpose: Converts an object to a matrix.
General Class: Data Manipulation
Required Argument(s):
x: An R object to be converted to a matrix.
Notable Optional Arguments:
ncol: Desired number of columns in the matrix. This is relevant when x is a vector, and you want to reshape it into a matrix with a specific number of columns.
nrow: Desired number of rows in the matrix. Similar to ncol, this is relevant when reshaping a vector.
Example:
# Example data for using the as.matrix function
vector_example <- c(1, 2, 3, 4, 5, 6)
# Use as.matrix to convert a vector to a matrix with 2 columns
matrix_result <- as.matrix(vector_example, ncol = 2)
# Display the result
print(matrix_result)In this example, the as.matrix function is used to convert a vector (vector_example) to a matrix (matrix_result) with 2 columns. The as.matrix function is versatile and can be used to convert various objects to a matrix, including vectors, data frames, and arrays.