col() Function in R with Example

The col() method returns a matrix of integers indicating their column number in a matrix-like object or a factor of column labels.

col() Function in R

The col() is a built-in function that gets the column number of a matrix. The col() method accepts two arguments and returns the number of a matrix.


col(x, dim, as.factor = FALSE)


  1. x: It is a matrix-like object that is one with a two-dimensional dim.
  2. dim: It is a matrix dimension, i.e., an integer-valued numeric vector of length two (with non-negative entries).
  3. as.factor: It is a logical value indicating whether the value should be returned as a factor of column labels (created if necessary) rather than numbers.

Return Value

The col() function returns an integer (or factor) matrix with the same dimensions as ‘x’ and whose ‘ij’-th element is equal to j (or the ‘j’-th column label).


To create a matrix in R, use the matrix() function.

vt_1 <- c(12, 2, 2, 6)
mtrx_1 <- matrix(vt_1, nrow = 2, ncol = 2)


     [,1]  [,2]
[1,]  12    2
[2,]  2     6

Now, let’s use the col() function to get the column number of a matrix.

vt_1 <- c(12, 2, 2, 6)
mtrx_1 <- matrix(vt_1, nrow = 2, ncol = 2)


     [,1] [,2]
[1,]   1    2
[2,]   1    2

That’s it for col() function in R.

See also

chol() Function in R

det() in R

Create an empty matrix in R

Leave a Comment