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 frameMy_Data_Frame <- data.frame (Height = c("Tall", "Average", "short"),Body_structure = c("Meso", "Endo", "Ecto"),Age = c(35, 30, 45))# printing the data frameprint(My_Data_Frame)# number of rowsnrow(My_Data_Frame)# number of columnsncol(My_Data_Frame)
Code explanation
- Line 2: We create a data frame variable,
My_Data_Frame, using thedata.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 thenrow()function. - Line 15: We check for the number of columns in the data frame,
My_Data_Frame, using thencol()function.
The code output tells us that the My_Data_Frame data frame contains 3 rows and 3 columns.