[Rd] Matrix package breaks as.matrix method
Robert McGehee
rmcgehee at walleyetrading.net
Fri Jan 27 23:41:10 CET 2017
Hi,
The Matrix package and the as.matrix method do not seem to be compatible inside of a package.
Here's an example. I've created a simple package "mat" that defines an eponymous class and as.matrix method on that class. All is well, unless that package has the Matrix package in its Depends or Imports (and imports, e.g. the "Diagonal" function). Then my as.matrix method stops working, even if I'm not using any part of the Matrix package.
Here's an example on R 3.3.2:
First, create an empty package "mat" (e.g. with package.skeleton) with one file in mat/R/mat.R with the following contents:
setClass("mat", representation(H="matrix"))
mat <- function(H) new("mat", H=H)
setMethod("as.matrix", signature("mat"), function(x, ...) crossprod(x at H))
testmat <- function() {
H <- matrix(1:3, 1, 3)
M <- mat(H)
as.matrix(M)
}
Then install the mat package :
> require(mat)
> testmat()
[,1] [,2] [,3]
[1,] 1 2 3
[2,] 2 4 6
[3,] 3 6 9
All works fine!
Now add "Depends: Matrix" into the package's DESCRIPTION file (alternatively add "Imports: Matrix" and 'importFrom("Matrix","Diagonal")' in the NAMESPACE).
Try again:
> require(mat)
> testmat()
Error in as.vector(data) :
no method for coercing this S4 class to a vector
Bug? If not, can anyone provide a work around? In my case, I'd like to mix matrix and Matrix functions in my package, but am obviously having difficulty.
I've come across a somewhat similar report on stackoverflow http://stackoverflow.com/questions/13812373/overloading-operator-in-r-s4-classes-and-matrix-package regarding defining the "+" operator with the Matrix package, but I don't think the solution or the problem quite applies.
Thanks in advance, Robert
> R.version
_
platform x86_64-pc-linux-gnu
arch x86_64
os linux-gnu
system x86_64, linux-gnu
status
major 3
minor 3.2
year 2016
month 10
day 31
svn rev 71607
language R
version.string R version 3.3.2 (2016-10-31)
nickname Sincere Pumpkin Patch
More information about the R-devel
mailing list