사이에 임의의 문자열 (일반적으로 연산자)이있는 행렬 및 벡터를 인쇄 할 수있는 매우 간단한 함수를 만들었습니다. 그것은 행 수가 다른 행렬을 허용하고 벡터를 열 행렬로 취급합니다. 그다지 정교하지는 않아서 실패하는 사례가 많이 있다는 것을 두려워합니다. 그러나 귀하의 질문에있는 것과 같은 간단한 예를 들면, 충분해야합니다.
format()
은 숫자를 문자로 변환하는 데 사용됩니다. 이것은 행렬의 모든 행이 동일한 너비를 가지므로 인쇄 할 때 잘 정렬됩니다. 필요한 경우 format()
의 인수 중 일부를 인수로 추가하여 mat_op_print()
을 구성 가능하게 만들 수 있습니다. 예를 들어, 열의 최소 너비를 제어하는 데 사용할 수있는 인수 width
을 추가했습니다.
함수 호출에서 행렬과 벡터가 이름 인 경우이 이름은 첫 번째 줄에 헤더로 인쇄됩니다. 그렇지 않으면 번호 만 인쇄됩니다.
그래서,이 함수이다
mat_op_print <- function(..., width = 0) {
# get arguments
args <- list(...)
chars <- sapply(args, is.character)
# auxilliary function to create character of n spaces
spaces <- function(n) paste(rep(" ", n), collapse = "")
# convert vectors to row matrix
vecs <- sapply(args, is.vector)
args[vecs & !chars] <- lapply(args[vecs & !chars], function(v) matrix(v, ncol = 1))
# convert all non-characters to character with format
args[!chars] <- lapply(args[!chars], format, width = width)
# print names as the first line, if present
arg_names <- names(args)
if (!is.null(arg_names)) {
get_title <- function(x, name) {
if (is.matrix(x)) {
paste0(name, spaces(sum(nchar(x[1, ])) + ncol(x) - 1 - nchar(name)))
} else {
spaces(nchar(x))
}
}
cat(mapply(get_title, args, arg_names), "\n")
}
# auxiliary function to create the lines
get_line <- function(x, n) {
if (is.matrix(x)) {
if (nrow(x) < n) {
spaces(sum(nchar(x[1, ])) + ncol(x) - 1)
} else {
paste(x[n, ], collapse = " ")
}
} else if (n == 1) {
x
} else {
spaces(nchar(x))
}
}
# print as many lines as needed for the matrix with most rows
N <- max(sapply(args[!chars], nrow))
for (n in 1:N) {
cat(sapply(args, get_line, n), "\n")
}
}
는 그리고 이것이 어떻게 작동의 예이다 :
A = matrix(c(0.5, 1, 3, 0.75, 2.8, 4), nrow = 2)
x = c(0.5, 3.7, 2.3)
y = c(0.7, -1.2)
b = A %*% x - y
mat_op_print(A = A, " * ", x = x, " - ", y = y, " = ", b = b, width = 6)
## A x y b
## 0.50 3.00 2.80 * 0.5 - 0.7 = 17.090
## 1.00 0.75 4.00 3.7 -1.2 13.675
## 2.3
또한 3 차원 어레이 나란히의 조각 인쇄 수 :
A <- array(1:12, dim = c(2, 2, 3))
mat_op_print(A1 = A[, , 1], " | ", A2 = A[, , 2], " | ", A3 = A[, , 3])
## A1 A2 A3
## 1 3 | 5 7 | 9 11
## 2 4 6 8 10 12
도움이 될 http://stackoverflow.com/questions/27513395/print-method-for-multiple-matrices – user20650