nrow

0th

Percentile

The Number of Rows/Columns of an Array

nrow and ncol return the number of rows or columns present in x. NCOL and NROW do the same treating a vector as 1-column matrix.

Keywords
array
Usage
nrow(x)
ncol(x)
NCOL(x)
NROW(x)
Arguments
x
a vector, array or data frame
Value

an integer of length 1 or NULL.

References

Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) The New S Language. Wadsworth & Brooks/Cole (ncol and nrow.)

See Also

dim which returns all dimensions; array, matrix.

Aliases
  • nrow
  • NROW
  • ncol
  • NCOL
Examples
library(base) ma <- matrix(1:12, 3, 4) nrow(ma) # 3 ncol(ma) # 4 ncol(array(1:24, dim = 2:4)) # 3, the second dimension NCOL(1:12) # 1 NROW(1:12) # 12
Documentation reproduced from package base, version 3.4.0, License: Part of R 3.4.0

Community examples

richie@datacamp.com at Jan 17, 2017 base v3.3.2

For matrices, nrow and ncol return the number of rows and columns. ```{r} m <- matrix(1:12, 3, 4) nrow(m) # 3 ncol(m) # 4 ``` `NROW()` and `NCOL()` behave exactly the same way. ```{r} m <- matrix(1:12, 3, 4) NROW(m) # 3 NCOL(m) # 4 ``` The same is true for data frames. ```{r} d <- data.frame(a = 1:3, b = 4:6, c = 7:9, d = 10:12) nrow(d) # 3 ncol(d) # 4 ``` For arrays, `nrow()` and `ncol()` refer to the first and second dimensions respectively. ```{r} a <- array(1:24, dim = 2:4) nrow(a) # 2 ncol(a) # 3 ``` For objects without a dim attribute, like vectors, `nrow ()` and `ncol()` are` NULL`, but `NROW()` and `NCOL()` treat the input like a column vector. ```{r} v <- 1:12 nrow(v) # NULL ncol(v) # NULL NROW(v) # 12 NCOL(v) # 1 ``` Note that objects with length zero (and no dim attribute) still have an `NCOL` of 1. ```{r} NROW(NULL) # 0 NCOL(NULL) # 1 ``` Functions have an `NROW` and `NCOL` of 1 (not the number of lines of code in the function body). ```{r} NROW(var) # 1 NCOL(var) # 1 ```