|
- my_matrix <- function(vec, nrow=NULL, ncol=NULL, colnames=NULL, rownames=NULL) {
- stopifnot("at least one of nrow or ncol has to be specified" = !is.null(nrow) || !is.null(ncol))
- if (is.null(nrow)) {
- stopifnot("incompatible length" = length(vec) %% ncol == 0)
- nrow <- length(vec) / ncol
- } else if (is.null(ncol)) {
- stopifnot("incompatible length" = length(vec) %% nrow == 0)
- ncol <- length(vec) / nrow
- } else if (length(vec) == 1) {
- vec <- rep(vec, nrow * ncol)
- } else stopifnot("incompatible length" = length(vec) == nrow * ncol)
-
- dim(vec) <- c(nrow, ncol)
- stopifnot("lenght of colnames must be ncol" = is.null(colnames) || length(colnames) == ncol)
- stopifnot("lenght of rownames must be nrow" = is.null(rownames) || length(rownames) == nrow)
- dimnames(vec) <- list(rownames, colnames)
- return(vec)
- }
-
- my_matrix(1:6)
- my_matrix(1:6, ncol=1)
- my_matrix(1:6, ncol=2)
- my_matrix(1:6, ncol=3)
- my_matrix(1:6, ncol=6)
- my_matrix(1:6, ncol=4)
- my_matrix(1:6, nrow=2)
- my_matrix(1:6, nrow=7)
- my_matrix(1:6, ncol=2, nrow=2)
- my_matrix(1:6, ncol=2, nrow=3)
- my_matrix(1:6, ncol=2, nrow=1)
- my_matrix(0, ncol=3, nrow=2)
- my_matrix(1:6, ncol=3, colnames=LETTERS[1:3])
- my_matrix(1:6, ncol=3, colnames=LETTERS[1:2])
- my_matrix(1:6, ncol=3, rownames=letters[24 + 1:2])
- my_matrix(1:6, ncol=3, colnames=LETTERS[1:3], rownames=letters[24 + 1:2])
|