How to Use ncol Function in R (With Examples)


You can use the ncol() function in R to count the number of columns in a data frame or matrix.

This function uses the following basic syntax:

ncol(x)

where:

  • x: Name of the data frame or matrix

The following examples show how use this function in different scenarios.

Example 1: Use ncol to Count Number of Columns in Data Frame

Suppose we have the following data frame in R:

#create data frame
df <- data.frame(team=c('A', 'B', 'C', 'D', 'E'),
                 points=c(99, 90, 86, 88, 95),
                 assists=c(33, 28, 31, 39, 34),
                 rebounds=c(30, 28, 24, 24, 28))

#view data frame
df

  team points assists rebounds
1    A     99      33       30
2    B     90      28       28
3    C     86      31       24
4    D     88      39       24
5    E     95      34       28

We can use the ncol() function to display the total number of columns in the data frame:

#display number of columns in data frame
ncol(df)

[1] 4

From the output we can see that there are 4 total columns in the data frame.

Example 2: Use ncol to Count Number of Columns in Matrix

Suppose we have the following matrix in R:

#create matrix
mat <- matrix(1:21, nrow=3)

#view matrix
mat

     [,1] [,2] [,3] [,4] [,5] [,6] [,7]
[1,]    1    4    7   10   13   16   19
[2,]    2    5    8   11   14   17   20
[3,]    3    6    9   12   15   18   21

We can use the ncol() function to display the total number of columns in the matrix:

#display number of columns in matrix
ncol(mat)

[1] 7

From the output we can see that there are 7 total columns in the matrix.

When to Use ncol Function in Practice

In practice, we often use the ncol function when we first load a new dataset into R so that we can quickly understand the size of a dataset.

This function is often used with nrow, which tells us the number of rows in a given dataset.

To quickly view the number of columns and rows in a dataset, you can use the dim function, which returns the dimensions of a dataset in terms of number of columns and rows.

The following code shows how to use these functions with a data frame in R:

#create data frame
df <- data.frame(team=c('A', 'B', 'C', 'D', 'E'),
                 points=c(99, 90, 86, 88, 95),
                 assists=c(33, 28, 31, 39, 34),
                 rebounds=c(30, 28, 24, 24, 28))

#display number of rows
nrow(df)

[1] 5

#display number of columns
ncol(df)

[1] 4

#display dimensions
dim(df)

[1] 5 4

From the output we can see that this data frame has 5 rows and 4 columns.

Additional Resources

The following tutorials explain how to perform other common tasks in R:

How to Use nrow Function in R
How to Select Specific Columns in R

Leave a Reply

Your email address will not be published. Required fields are marked *