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, even a 0-length vector, compatibly with as.matrix() or cbind(), see the example.

Keywords
array
nrow(x)
ncol(x)
NCOL(x)
NROW(x)
Arguments
x

a vector, array, data frame, or NULL.

Value

an integer of length 1 or NULL, the latter only for ncol and nrow.

References

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

dim which returns all dimensions; array, matrix.

• nrow
• NROW
• ncol
• NCOL
Examples
library(base) # NOT RUN { 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 ## as.matrix() produces 1-column matrices from 0-length vectors, ## and so does cbind() : dim(as.matrix(numeric())) # 0 1 dim( cbind(numeric())) # ditto ## consequently, NCOL(.) gives 1, too : NCOL(numeric()) # 1 and hence NCOL(NULL) # 1 # }
Documentation reproduced from package base, version 3.6.0, License: Part of R 3.6.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