Importing S4 functions from the Matrix package
Asked Answered
B

1

13

The Matrix package defines a whole bunch of S4 methods for multiplying matrices, that are dispatched by the S4 generic functions %*%, crossprod, and tcrossprod.

How do I import the "%*%" methods, for use in my own package? This piece of code fails when I run devtools::document():

#' @title my function
#'
#' @description Does magic Matrix stuff
#' @import methods
#' @importFrom Matrix "%*%" Diagonal
myfun <- function(x, y){
  x %*% Diagonal(x=y)
}

I want to make sure this function uses the sparse Matrix multiplication methods from the Matrix package if x is a sparse matrix. But when I run devtools::document() I get the following error:

Updating mypackage documentation
Loading mypackage
Error: object ‘%*%’ is not exported by 'namespace:Matrix'
Barbel answered 6/11, 2014 at 15:56 Comment(2)
Read the last section there: r-pkgs.had.co.nz/namespace.htmlYestreen
@import methods did not fix my problem, nor did @importMethodsFrom Matrix "%*%".Barbel
E
12

You should use @importMethodsFrom and remove the quotes around the operator. You probably also want to export the function with @export (you may already know this but it makes the answer more complete). The following works for me without error.

#' @title my function
#'
#' @description Does magic Matrix stuff
#' @import methods
#' @importFrom Matrix Diagonal
#' @importMethodsFrom Matrix %*%
#' @export
myfun <- function(x, y){
    x %*% Diagonal(x=y)
}
Emulsifier answered 4/5, 2015 at 17:41 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.