ncol

ncol is a function that returns the number of columns of a matrix, vector, array or data frame.

Examples

How do I get the number of columns of a dataset?

Click to see solution

Let’s first take a look at our dataset.

# Getting R Biochemical Oxygen Demand Dataset
BOD
Time demand
1    1    8.3
2    2   10.3
3    3   19.0
4    4   16.0
5    5   15.6
6    7   19.8

Since we have 2 columns, we want our nrow function to return the value 2. Let’s try it out!

ncol(BOD)
[1] 2

How do I get the number of columns of a matrix?

Click to see solution
# Let's specify a matrix assigned to the variable x.
x <- matrix(c(1, 2, 3, 4), 1, 4)
ncol(x)
[1] 2