Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

function
r
communitycreator

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

Onyejiaku Theophilus Chidalu

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)
Implementing the nrow() and ncol() functions

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.

RELATED TAGS

function
r
communitycreator

CONTRIBUTOR

Onyejiaku Theophilus Chidalu
RELATED COURSES

View all Courses

Keep Exploring