Number of Columns in R Data Frame

To get number of columns in R Data Frame, call ncol() function and pass the data frame as argument to this function.

ncol() is a function in R base package.

In this tutorial, we will learn how to use ncol() function to get number of columns in the Data Frame.

Syntax

The syntax to call ncol() function to get the number of columns in given data frame is

</>
Copy
ncol(df)

where

df is the Data Frame for which we would like to find the number of columns.

Return Value

ncol() returns an integer value or NULL value.

Examples

In the following program, we create a data frame, and find the number of columns in it using ncol() function.

Example.R

</>
Copy
#create data frame
df <- data.frame("c1" = c(41, 42, 43, 44),
                 "c2" = c(45, 46, 47, 48),
                 "c3" = c(49, 50, 51, 52))
#find number of columns
n <- ncol(df)
#print
cat("Number of columns in Data Frame :", n)

Output

Number of columns in Data Frame : 3

Now, let us take an empty data frame, and find the number of columns in it. ncol() should return 0, since there are no columns in the data frame.

Example.R

</>
Copy
#create data frame
df <- data.frame()
#find number of columns
n <- ncol(df)
#print
cat("Number of columns in Data Frame :", n)

Output

Number of columns in Data Frame : 0

Conclusion

In this R Tutorial, we learned to get the number of columns in an R Data Frame using ncol() function, with the help of examples.