To get the number of columns in a matrix in R, you can use the ncol()
function, which returns the number of columns present in the given matrix.
In this example,
matrix1
using the matrix()
function and specify the elements and dimensions. The matrix()
function takes a vector of values and arranges them into the specified number of rows and columns.ncol()
function to get the number of columns in matrix1
. The ncol()
function takes the matrix as an argument and returns the number of columns.numCols
.numCols
using the print()
function to display the number of columns in the matrix.matrix1 <- matrix(1:9, nrow = 3, ncol = 3)
numCols <- ncol(matrix1)
print(paste("Number of columns in matrix1 is:", numCols))
Number of columns in matrix1 is: 3
In this example,
matrix2
using the matrix()
function and specify the elements and dimensions. The matrix()
function takes a vector of values and arranges them into the specified number of rows and columns.ncol()
function to get the number of columns in matrix2
. The ncol()
function takes the matrix as an argument and returns the number of columns.numCols
.numCols
using the print()
function to display the number of columns in the matrix.matrix2 <- matrix(1:8, nrow = 4, ncol = 2)
numCols <- ncol(matrix2)
print(paste("Number of columns in matrix2 is:", numCols))
Number of columns in matrix2 is: 2
In this example,
matrix3
using the matrix()
function and specify the elements and dimensions. The matrix()
function takes a vector of values and arranges them into the specified number of rows and columns.ncol()
function to get the number of columns in matrix3
. The ncol()
function takes the matrix as an argument and returns the number of columns.numCols
.numCols
using the print()
function to display the number of columns in the matrix.matrix3 <- matrix(1:25, nrow = 5, ncol = 5)
numCols <- ncol(matrix3)
print(paste("Number of columns in matrix3 is:", numCols))
Number of columns in matrix3 is: 5
In this tutorial, we learned How to get Number of Columns in Matrix in R language with well detailed examples.