Für Vorlesungen, bitte die Webseite verwenden. https://flavigny.de/lecture
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

36 line
1.4KB

  1. my_matrix <- function(vec, nrow=NULL, ncol=NULL, colnames=NULL, rownames=NULL) {
  2. stopifnot("at least one of nrow or ncol has to be specified" = !is.null(nrow) || !is.null(ncol))
  3. if (is.null(nrow)) {
  4. stopifnot("incompatible length" = length(vec) %% ncol == 0)
  5. nrow <- length(vec) / ncol
  6. } else if (is.null(ncol)) {
  7. stopifnot("incompatible length" = length(vec) %% nrow == 0)
  8. ncol <- length(vec) / nrow
  9. } else if (length(vec) == 1) {
  10. vec <- rep(vec, nrow * ncol)
  11. } else stopifnot("incompatible length" = length(vec) == nrow * ncol)
  12. dim(vec) <- c(nrow, ncol)
  13. stopifnot("lenght of colnames must be ncol" = is.null(colnames) || length(colnames) == ncol)
  14. stopifnot("lenght of rownames must be nrow" = is.null(rownames) || length(rownames) == nrow)
  15. dimnames(vec) <- list(rownames, colnames)
  16. return(vec)
  17. }
  18. my_matrix(1:6)
  19. my_matrix(1:6, ncol=1)
  20. my_matrix(1:6, ncol=2)
  21. my_matrix(1:6, ncol=3)
  22. my_matrix(1:6, ncol=6)
  23. my_matrix(1:6, ncol=4)
  24. my_matrix(1:6, nrow=2)
  25. my_matrix(1:6, nrow=7)
  26. my_matrix(1:6, ncol=2, nrow=2)
  27. my_matrix(1:6, ncol=2, nrow=3)
  28. my_matrix(1:6, ncol=2, nrow=1)
  29. my_matrix(0, ncol=3, nrow=2)
  30. my_matrix(1:6, ncol=3, colnames=LETTERS[1:3])
  31. my_matrix(1:6, ncol=3, colnames=LETTERS[1:2])
  32. my_matrix(1:6, ncol=3, rownames=letters[24 + 1:2])
  33. my_matrix(1:6, ncol=3, colnames=LETTERS[1:3], rownames=letters[24 + 1:2])