The ncol function is used to get number of columns in data frame,matrix or table like structure in R.

The following method shows how you can do it with syntax.

Method: Use ncol() Function

ncol(df)


The following examples show how to use ncol() function in R.

## Use ncol() Function to Get Number of Columns of Data Frame

Let’s see how to find number of columns of data frame using ncol() function:

# Create data frame
df <- data.frame(Machine_name=c("A","B","C","D","A","A","G","B"),
Temperature=c(12,9,NA,13,18,28,22,23),
Pressure=c(20,25,27,29,30,32,39,40))

# Find total number columns
ncol(df)


Output:

[1] 3


As in the above code ncol() function returns 3 since data frame having 3 columns.

## Use ncol() Function to Get Number of Columns of Matrix

Suppose we want to find number of column of matrix using ncol() function:

# Create matrix
matrix1 <- matrix(c(12,9,15,13,18,28,22,23,20,25,27,29,30,32,39,40),nrow=4)

# Show matrix
print(matrix1)

# Find total number columns of matrix
ncol(matrix1)


Output:

     [,1] [,2] [,3] [,4]
[1,]   12   18   20   30
[2,]    9   28   25   32
[3,]   15   22   27   39
[4,]   13   23   29   40

[1] 4


As the output shows matrix with its number of columns.