What are the ncol() and nrow() functions for a data frame in R?

Overview

The nrow() and ncol() functions find the number of rows and columns of a given data frame respectively.

Syntax

nrow(dataframe)
ncol(dataframe)

Parameter value

Both the nrow() and ncol() functions take the same parameter value. This value represents the data frame object whose number of rows and columns is to be determined.

Return value

The nrow() function returns the number of rows present in a given data frame, while the ncol() function returns the number of columns present in a data frame.

Code example

# creating a data frame
My_Data_Frame <- data.frame (
Height = c("Tall", "Average", "short"),
Body_structure = c("Meso", "Endo", "Ecto"),
Age = c(35, 30, 45)
)
# printing the data frame
print(My_Data_Frame)
# number of rows
nrow(My_Data_Frame)
# number of columns
ncol(My_Data_Frame)

Code explanation

  • Line 2: We create a data frame variable, My_Data_Frame, using the data.frame() function. The data frame contains three columns.
  • Line 9: We print the data frame My_Data_Frame.
  • Line 12: We check for the number of rows in the data frame, My_Data_Frame, using the nrow() function.
  • Line 15: We check for the number of columns in the data frame, My_Data_Frame, using the ncol() function.

The code output tells us that the My_Data_Frame data frame contains 3 rows and 3 columns.

New on Educative
Learn to Code
Learn any Language as a beginner
Develop a human edge in an AI powered world and learn to code with AI from our beginner friendly catalog
🏆 Leaderboard
Daily Coding Challenge
Solve a new coding challenge every day and climb the leaderboard

Free Resources