This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
as_tidymatrix <- function(x){ | |
structure(list(.value = as.vector(x), | |
.row = as.vector(row(x)), | |
.col = as.vector(col(x))), | |
row.names = seq_len(length(as.vector(x))), | |
nrow = nrow(x), # need these attribute if storing it as sparse later | |
ncol = ncol(x), | |
class = c("tidymatrix", "data.frame")) | |
} | |
as.matrix.tidymatrix <- function(x) { | |
matrix(data = x$.value, | |
nrow = attr(x, "nrow"), | |
ncol = attr(x, "ncol")) | |
} | |
`%*%.tidymatrix` <- function(x, y) { | |
res <- as.matrix(x) %*% as.matrix(y) | |
as_tidymatrix(res) | |
} | |
x <- as_tidymatrix(matrix(1:6, nrow = 2)) | |
y <- as_tidymatrix(matrix(1:9, nrow = 3)) | |
x %*% y | |
# error -> Primitive("%*%") has some check built-in :( | |
# requires numeric/complex matrix/vector arguments |
Author
emitanaka
commented
Apr 1, 2021
•
This works. Thanks Brenton Wiernik for the info.
`%*%` <- function(x, y) {
UseMethod("%*%")
}
`%*%.matrix` <- function(x, y) {
.Primitive("%*%")(x, y)
}
`%*%.tidymatrix` <- function(x, y) {
res <- as.matrix(x) %*% as.matrix(y)
as_tidymatrix(res)
}
x <- as_tidymatrix(matrix(1:6, nrow = 2))
y <- as_tidymatrix(matrix(1:9, nrow = 3))
x %*% y
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment