 # ncol in R: Count the number of the columns in the R object In this tutorial, we will share with you what the ncol in R is and how to use the ncol() function in R. The ncol in R can help you count the number of columns in the R object. Follow this guide to learn more about it with the explanation and examples below.

## What does the ncol() function do in R?

The ncol() function in R helps you count the number of columns in the R object such as: matrix, data frame. But note that when you use this function with the vector. The function will return NULL. If you want to use the vector as the 1-column matrix, you can use the NCOL() function.

Syntax:

ncol(x)

Parameters:

• x: The R object: a vector, an array, a matrix, or a data frame.

Return value:

This function will return the value as an integer or NULL.

## How to use the ncol() function in R?

The ncol in R is used to count the columns of the R object. Follow us to learn more about this function by the following examples below.

### Count the columns of the matrix

You can count the columns of a matrix by the ncol() function. If you are not similar while working with the matrix. Click here to learn how to create the matrix in R.

Example:

# Create the new matrix
matrix <- matrix(1:15, nrow = 3, ncol = 5)
matrix

Output:

    [,1] [,2] [,3] [,4] [,5]
[1,]  1    4    7   10   13
[2,]  2    5    8   11   14
[3,]  3    6    9   12   15

Use the ncol() function to count the columns of this matrix.

matrix <- matrix(1:15, nrow = 3, ncol = 5)
ncol(matrix)

Output:

 5

### Count the columns of the data frame

You can count the columns of the data frame by the ncol() function.

Example:

# Create the data frame, which is the top 5 scores of the world cup in 2022
df <- data.frame(
name = c("Mbappe", "Richarlison", "Ramos", "Messi", "Rashford"),
goals = c(5, 3, 3, 3, 3)
)

df

Output

   name     goals
1 Mbappe      5
2 Richarlison 3
3 Ramos       3
4 Messi       3
5 Rashford    3

Count the columns of this data frame.

# Create the data frame, which is the top 5 scores of the world cup in 2022
df <- data.frame(
name = c("Mbappe", "Richarlison", "Ramos", "Messi", "Rashford"),
goals = c(5, 3, 3, 3, 3)
)

ncol(df)

Output

 2

### Use the ncol() function with the vector

When you use the ncol() function with the vector. The function will return NULL.

Example:

vec <- c(1, 2, 3, 4, 5)
ncol(vec)

Output

NULL

If you want to use the vector as the 1-column matrix, you can use the NCOL() function instead.

vec <- c(1, 2, 3, 4, 5)
NCOL(vec)

Output

 1

## Summary

You have learned about what the ncol in R is, and how to use the ncol in R. By the ncol() function, you can count the number of columns in the R object. Leave your comments below if you have any questions about this guide. I will answer your questions. We hope this guide is helpful to you. Thanks!

Maybe you are interested:

Posted in R