Open In App

Getting a Matrix of number of rows in R Programming – row() Function

Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will discuss how to find the number of rows and columns in a matrix in R Programming Language.

nrow() Function in R

nrow() function in R Language is used to get the row number of a matrix.

Syntax: 

row(x, as.factor=FALSE)

Parameters:
x: matrix
as.factor: a logical value indicating whether the value should be returned as a factor of column labels (created if necessary) rather than as numbers

ncol() Function in R

The ncol() function in R is used to get the number of columns in a matrix.

Find number of rows and columns in a Basic Matrix

R




# Create an irregular matrix
irregular_mat <- matrix(1:9,3,3)
 
# Find the number of rows and columns
num_rows_irregular <- nrow(irregular_mat)
num_cols_irregular <- ncol(irregular_mat)
 
# Print the results
print(paste("Number of rows in irregular matrix:", num_rows_irregular))
print(paste("Number of columns in irregular matrix:", num_cols_irregular))


Output:

[1] "Number of rows in irregular matrix: 3"
[1] "Number of columns in irregular matrix: 3"

Find number of rows and columns in a Irregular Matrix in R

R




# Create a 3x4 matrix
mat <- matrix(1:24,6,4)
mat
 
# Find the number of rows and columns
num_rows <- nrow(mat)
num_cols <- ncol(mat)
 
# Print the results
print(paste("Number of rows:", num_rows))
print(paste("Number of columns:", num_cols))


Output:

     [,1] [,2] [,3] [,4]
[1,] 1 7 13 19
[2,] 2 8 14 20
[3,] 3 9 15 21
[4,] 4 10 16 22
[5,] 5 11 17 23
[6,] 6 12 18 24
[1] "Number of rows: 6"
[1] "Number of columns: 4"


Last Updated : 20 Dec, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads