# The ncol Function in R (3 Examples)

**Basic R Syntax:**

ncol(data) |

ncol(data)

The ncol R function **returns the number of columns** of a matrix or data frame. Above, you can find the command for the application of ncol in the R programming language.

You’d like to hear some more details? In the following tutorial, I’ll provide you with several **examples of the usage** of the ncol function in R.

## Example 1: Count Number of Columns of a Data Frame

Before we can dive into the application of the ncol command in R, let’s create an example data frame:

set.seed(99999) # Seed for reproducibility N <- 100 # Sample size x1 <- round(runif(N, 1, 10)) # Column 1 x2 <- round(runif(N, 0, 3)) # Column 2 x3 <- round(runif(N, 1, 5)) # Column 3 data_frame <- data.frame(x1, x2, x3) # Data frame with 3 columns head(data_frame) # First 6 rows |

set.seed(99999) # Seed for reproducibility N <- 100 # Sample size x1 <- round(runif(N, 1, 10)) # Column 1 x2 <- round(runif(N, 0, 3)) # Column 2 x3 <- round(runif(N, 1, 5)) # Column 3 data_frame <- data.frame(x1, x2, x3) # Data frame with 3 columns head(data_frame) # First 6 rows

**Table 1: Example Data for the Application of the ncol R function.**

As you can see based on Table 1, our data frame consists of 3 columns. Let’s check how we could investigate on that with the ncol function in R:

ncol(data_frame) # Count the number of columns # 3 |

ncol(data_frame) # Count the number of columns # 3

ncol returns the number 3 – seems correct!

## Example 2: Count the Number of Columns of a Matrix

The ncol function is easy to apply – also to matrices! Even if our data has the class matrix, we can apply the ncol command in the same manner.

First, let’s convert the data frame we used before into a matrix:

mat <- as.matrix(data_frame) |

mat <- as.matrix(data_frame)

Then, let’s apply the ncol function:

ncol(mat) # 3 |

ncol(mat) # 3

Still 3 – very good.

## Example 3: ncol Returns NULL – A Common Mistake

A mistake that I see quite often is that people try to apply ncol to a vector (often, because they falsely think that their data is in data frame or matrix format).

The result is that R returns NULL, instead of the number of columns. Confusing…

I’ll illustrate that with some R code:

set.seed(716253) # Set seed vec1 <- rnorm(10, 5, 2) # Some random data vector ncol(vec1) # Apply the ncol R command # NULL |

set.seed(716253) # Set seed vec1 <- rnorm(10, 5, 2) # Some random data vector ncol(vec1) # Apply the ncol R command # NULL

As you can see, the ncol command is not working for vectors. If you want to know the amount of values of a vector, you have to use the transpose function…

ncol(t(vec1)) # Transpose function in R # 10 |

ncol(t(vec1)) # Transpose function in R # 10

…or even easier: the length function.

length(vec1) # Length function in R # 10 |

length(vec1) # Length function in R # 10

## Video Examples: ncol and Similar R Functions in Practice

Do you need more examples? No problem! Have a look at the following YouTube video of Richard Webster.

## Further Reading

### Subscribe to my free statistics newsletter:

### R Tutorials

abs Function in R

all & any R Functions

Set Aspect Ratio of Plot

attach & detach R Functions

attr, attributes & structure in R

cbind R Command

Change ggplot2 Legend Title

Character to Numeric in R

Check if Object is Defined

col & row sums, means & medians

Complete Cases in R

Concatenate Vector of Strings

Convert Date to Weekday

cumsum R Function

Data Frame Column to Numeric

diff Command in R

difftime R Function

dim Function in R

dir R Function

Disable Scientific Notation

Draw Segments in R

droplevels R Example

Evaluate an Expression

Extract Characters from String

Factor to Numeric in R

Format Decimal Places

get, get0 & mget in R

is.na R Function

is.null Function in R

jitter R Function

Join Data with dplyr Package

length Function in R

lowess R Smoothing Function

max and min Functions in R

NA Omit in R

nchar R Function

ncol Function in R

nrow Function in R

outer Function in R

pairs & ggpairs Plot

parse, deparse & R expression

paste & paste0 Functions in R

pmax and pmin R Functions

polygon Plots in R

pretty R Function

R Find Missing Values

R Functions List (+ Examples)

R NA – Values

R Replace NA with 0

rbind & rbind.fill in R

Read Excel Files in R

readLines, n.readLines & readline

Remove Element from List

Remove Legend in ggplot2

Rename Column Name in R

Replace Last Comma of String

rev R Command

Round Numeric Data in R

Save & Load RData Workspace

scan R Function

setdiff R Function

setNames vs. setnames in R

sink Command in R

Sort, Order & Rank Data in R

sprintf Function in R

Square Root in R

str_c Function of stringr Package

str_sub Function of stringr Package

strptime & strftime Functions

substr & substring R Commands

sweep R Function

Transform Data Frames

union Function in R

unlist in R

weekdays, months, quarters & julian in R

with & within R Functions

Write Excel File in R