top of page
Writer's pictureEkta Aggarwal

dim, nrow, ncol in R - Number of rows and columns in a dataframe

In this tutorial we will learn about how to get the number of rows and columns of a dataframe.


For this, we will make use of mtcars dataset, which is inbuilt in R.


View Command:

Let us firstly view the mtcars dataset using View commmand. In the snapshot you can see that in the bottom it is mentioned Showing 1 to 19 of 32 entries, 11 total columns: This gives an idea that mtcars has 32 entries i.e., rows and 11 columns.

View(mtcars)

nrow Command:

Using nrow command one can get the number of rows of a dataset. In the output you can see we will get 32, i.e., mtcars has 32 rows.

nrow(mtcars)

Output: 32


Similarly if we try nrow on iris dataset, then we can see that iris has 150 rows.

nrow(iris)

Output: 150


ncol Command:

Using ncol command one can get the number of columns of a dataset. In the output you can see we will get 11, i.e., mtcars has 11 columns

ncol(mtcars)

Output: 11


Similarly if we try ncol on iris dataset, then we can see that iris has 5 columns

ncol(iris)

Output: 5



dim Command:


dim stands for dimensions. Using dim command one can get both number of rows and columns of a dataset.


In the output you can see we will get 32 11. Here the first number represents the number of rows and second number represents the number of columns i.e., mtcars has 32 rows and 11 columns

dim(mtcars)

Output: 32 11


Similarly if we try dim on iris dataset, then we can see that iris has 150 rows and 5 columns

dim(iris)

Output: 150 5


We can also get number of rows using dim function. Since dim function returns a vector of 2 elements i.e., the first element is the number of rows and second is number of columns, thus we can retrieve the number of rows by writing [1] after dim function

dim(mtcars)[1]

Output: 32


We can also get number of columns using dim function. Since dim function returns a vector of 2 elements i.e., the first element is the number of rows and second is number of columns, thus we can retrieve the number of columns by writing [2] after dim function

dim(mtcars)[2]

Output: 11

Comments


bottom of page