# SCM Repository

[matrix] Diff of /pkg/R/Matrix.R
 [matrix] / pkg / R / Matrix.R

# Diff of /pkg/R/Matrix.R

revision 1290, Thu Jun 8 09:30:21 2006 UTC revision 2112, Mon Feb 18 08:24:46 2008 UTC
# Line 1  Line 1
1  #### Toplevel ``virtual'' class "Matrix"  #### Toplevel ``virtual'' class "Matrix"
2
3
4    ### Virtual coercions -- via smart "helpers" (-> ./Auxiliaries.R)
5
6    setAs("Matrix", "sparseMatrix", function(from) as(from, "CsparseMatrix"))
7    setAs("Matrix", "CsparseMatrix", function(from) as_Csparse(from))
8    setAs("Matrix", "denseMatrix",  function(from) as_dense(from))
9
10    ## Maybe TODO:
11    ## setAs("Matrix", "nMatrix", function(from) ....)
12
13    ## Most of these work; this is a last resort:
14    setAs(from = "Matrix", to = "matrix", # do *not* call base::as.matrix() here:
15          function(from) .bail.out.2("coerce", class(from), class(to)))
16    setAs(from = "matrix", to = "Matrix", function(from) Matrix(from))
17
18  ## ## probably not needed eventually:  ## ## probably not needed eventually:
19  ## setAs(from = "ddenseMatrix", to = "matrix",  ## setAs(from = "ddenseMatrix", to = "matrix",
20  ##       function(from) {  ##       function(from) {
# Line 12  Line 27
27  ## for 'Matrix' objects, as.array() should be equivalent:  ## for 'Matrix' objects, as.array() should be equivalent:
28  setMethod("as.array",  signature(x = "Matrix"), function(x) as(x, "matrix"))  setMethod("as.array",  signature(x = "Matrix"), function(x) as(x, "matrix"))
29
30    ## head and tail apply to all Matrix objects for which subscripting is allowed:
32    setMethod("tail", signature(x = "Matrix"), utils::tail.matrix)
33
34    setMethod("drop", signature(x = "Matrix"),
35              function(x) if(all(dim(x) != 1)) x else drop(as(x, "matrix")))
36
37  ## slow "fall back" method {subclasses should have faster ones}:  ## slow "fall back" method {subclasses should have faster ones}:
38  setMethod("as.vector", signature(x = "Matrix", mode = "missing"),  setMethod("as.vector", signature(x = "Matrix", mode = "missing"),
39            function(x) as.vector(as(x, "matrix")))            function(x) as.vector(as(x, "matrix")))
40
41    ## mainly need these for "dMatrix" or "lMatrix" respectively, but why not general:
42    setMethod("as.numeric", signature(x = "Matrix"),
43              function(x, ...) as.numeric(as.vector(x)))
44    setMethod("as.logical", signature(x = "Matrix"),
45              function(x, ...) as.logical(as.vector(x)))
46
47    setMethod("cov2cor", signature(V = "Matrix"),
48              function(V) as(cov2cor(as(V, "matrix")), "dpoMatrix"))
49
50  ## Note that isSymmetric is *not* exported  ## "base" has an isSymmetric() S3-generic since R 2.3.0
## but that "base" has an isSymmetric() S3-generic since R 2.3.0
51  setMethod("isSymmetric", signature(object = "symmetricMatrix"),  setMethod("isSymmetric", signature(object = "symmetricMatrix"),
52            function(object,tol) TRUE)            function(object, ...) TRUE)
53  setMethod("isSymmetric", signature(object = "triangularMatrix"),  setMethod("isSymmetric", signature(object = "triangularMatrix"),
54            ## TRUE iff diagonal:            ## TRUE iff diagonal:
55            function(object,tol) isDiagonal(object))            function(object, ...) isDiagonal(object))

if(paste(R.version\$major, R.version\$minor, sep=".") < "2.3")
## need a "matrix" method as in R 2.3 and later
setMethod("isSymmetric", signature(object = "matrix"),
function(object, tol = 100*.Machine\$double.eps, ...)
{
## pretest: is it square?
d <- dim(object)
if(d[1] != d[2]) return(FALSE)
## for `broken' all.equal in R <= 2.2.x:
dn <- dimnames(object)
if(!identical(dn[1], dn[2])) return(FALSE)
test <-
if(is.complex(object))
all.equal.numeric(object, Conj(t(object)), tol = tol, ...)
else              # numeric, character, ..
all.equal(object, t(object), tol = tol, ...)
isTRUE(test)
})

setMethod("isTriangular", signature(object = "triangularMatrix"),
function(object, ...) TRUE)
56
57  setMethod("isTriangular", signature(object = "matrix"), isTriMat)  setMethod("isTriangular", signature(object = "matrix"), isTriMat)
58
59  setMethod("isDiagonal", signature(object = "matrix"), .is.diagonal)  setMethod("isDiagonal", signature(object = "matrix"), .is.diagonal)
60
61    ## The "catch all" methods -- far from optimal:
62    setMethod("symmpart", signature(x = "Matrix"),
63              function(x) as((x + t(x))/2, "symmetricMatrix"))
64    setMethod("skewpart", signature(x = "Matrix"),
65              function(x) (x - t(x))/2)
66
67    ## FIXME: do this (similarly as for "ddense.." in C
68    setMethod("symmpart", signature(x = "matrix"), function(x) (x + t(x))/2)
69    setMethod("skewpart", signature(x = "matrix"), function(x) (x - t(x))/2)
70
71
72
73
74  setMethod("dim", signature(x = "Matrix"),  setMethod("dim", signature(x = "Matrix"),
75            function(x) x@Dim, valueClass = "integer")            function(x) x@Dim, valueClass = "integer")
76
77    setMethod("length", "Matrix", function(x) prod(dim(x)))
78
79  setMethod("dimnames", signature(x = "Matrix"), function(x) x@Dimnames)  setMethod("dimnames", signature(x = "Matrix"), function(x) x@Dimnames)
80
81
82  ## not exported but used more than once for "dimnames<-" method :  ## not exported but used more than once for "dimnames<-" method :
83  ## -- or do only once for all "Matrix" classes ??  ## -- or do only once for all "Matrix" classes ??
84  dimnamesGets <- function (x, value) {  dimnamesGets <- function (x, value) {
# Line 75  Line 97
97  setMethod("unname", signature("Matrix", force="missing"),  setMethod("unname", signature("Matrix", force="missing"),
98            function(obj) { obj@Dimnames <- list(NULL,NULL); obj})            function(obj) { obj@Dimnames <- list(NULL,NULL); obj})
99
100    setMethod("all", signature(x = "Matrix"),
101              function(x, ..., na.rm)
102              callGeneric(as(x, "lMatrix"), ..., na.rm=na.rm))
103
104    setMethod("any", signature(x = "Matrix"),
105              function(x, ..., na.rm)
106              callGeneric(as(x, "lMatrix"), ..., na.rm=na.rm))
107
108    ## NOTE:  "&" and "|"  are now in group "Logic" c "Ops" --> ./Ops.R
109    ##        "!" is in ./not.R
110
111
112  Matrix <-  Matrix <-
113      function (data = NA, nrow = 1, ncol = 1, byrow = FALSE, dimnames = NULL,      function (data = NA, nrow = 1, ncol = 1, byrow = FALSE, dimnames = NULL,
114                sparse = NULL)                sparse = NULL, forceCheck = FALSE)
115  {  {
116      sparseDefault <- function(m)      sparseDefault <- function(m) prod(dim(m)) > 2*sum(isN0(as(m, "matrix")))
prod(dim(m)) > 2*sum(as(m, "matrix") != 0)
117
118      i.M <- is(data, "Matrix")      i.M <- is(data, "Matrix")
119      if(is.null(sparse) && (i.M || is(data, "matrix")))      if(!i.M && inherits(data, "table")) # special treatment
120            class(data) <- "matrix" # "matrix" first for S4 dispatch
121        if(is.null(sparse1 <- sparse) && (i.M || is(data, "matrix")))
122          sparse <- sparseDefault(data)          sparse <- sparseDefault(data)
123
124        doDN <- TRUE
125      if (i.M) {      if (i.M) {
126            if(!missing(nrow) || !missing(ncol)|| !missing(byrow))
127                warning("'nrow', 'ncol', etc, are disregarded when 'data' is \"Matrix\" already")
128          sM <- is(data,"sparseMatrix")          sM <- is(data,"sparseMatrix")
129          if((sparse && sM) || (!sparse && !sM))          if(!forceCheck && ((sparse && sM) || (!sparse && !sM)))
130              return(data)              return(data)
131          ## else : convert  dense <-> sparse -> at end          ## else : convert  dense <-> sparse -> at end
132      }      }
# Line 97  Line 135
135              nrow <- ceiling(length(data)/ncol)              nrow <- ceiling(length(data)/ncol)
136          else if (missing(ncol))          else if (missing(ncol))
137              ncol <- ceiling(length(data)/nrow)              ncol <- ceiling(length(data)/nrow)
138            if(length(data) == 1 && is0(data) && !identical(sparse, FALSE)) {
139                ## Matrix(0, ...) : always sparse unless "sparse = FALSE":
140                if(is.null(sparse)) sparse1 <- sparse <- TRUE
141                i.M <- sM <- TRUE
142                ## will be sparse: do NOT construct full matrix!
143                data <- new(if(is.numeric(data)) "dgTMatrix" else
144                            if(is.logical(data)) "lgTMatrix" else
145                            stop("invalid 'data'"),
146                            Dim = as.integer(c(nrow,ncol)),
147                            Dimnames = if(is.null(dimnames)) list(NULL,NULL)
148                            else dimnames)
149            } else { ## normal case - using .Internal() to avoid more copying
150                if(getRversion() >= "2.7.0")
151                    data <- .Internal(matrix(data, nrow, ncol, byrow, dimnames))
152                else {
153          data <- .Internal(matrix(data, nrow, ncol, byrow))          data <- .Internal(matrix(data, nrow, ncol, byrow))
154                    dimnames(data) <- dimnames
155                }
156          if(is.null(sparse))          if(is.null(sparse))
157              sparse <- sparseDefault(data)              sparse <- sparseDefault(data)
158          dimnames(data) <- dimnames          }
159      } else if (!is.null(dimnames))          doDN <- FALSE
160          dimnames(data) <- dimnames      } else if(!missing(nrow) || !missing(ncol)|| !missing(byrow))
161            warning("'nrow', 'ncol', etc, are disregarded for matrix 'data'")
162
163      ## 'data' is now a "matrix" or "Matrix"      ## 'data' is now a "matrix" or "Matrix"
164        if (doDN && !is.null(dimnames))
165            dimnames(data) <- dimnames
166
167      ## check for symmetric / triangular / diagonal :      ## check for symmetric / triangular / diagonal :
168      isSym <- isSymmetric(data)      isSym <- isSymmetric(data)
# Line 114  Line 172
172      if(isDiag)      if(isDiag)
173          isDiag <- isDiagonal(data)          isDiag <- isDiagonal(data)
174
### TODO: Compare with as.Matrix() and its tests in ./dgeMatrix.R

175      ## Find proper matrix class 'cl'      ## Find proper matrix class 'cl'
176      cl <-      cl <-
177          if(isDiag)          if(isDiag && !isTRUE(sparse1))
178              "diagonalMatrix" # -> will automatically check for type              "diagonalMatrix" # -> will automatically check for type
179          else {          else {
180              ## consider it's type              ## consider it's type
# Line 146  Line 202
202                    }, sep="")                    }, sep="")
203          }          }
204
205      ## Now coerce and return      ## Can we coerce and be done?
206        if(!canCoerce(data,cl)) { ## try to coerce ``via'' virtual classes
207            if(sparse && !sM)
208                data <- as(data, "sparseMatrix")
209            else if(!sparse && !is(data, "denseMatrix"))
210                data <- as(data, "denseMatrix")
211            if(isTri && !is(data, "triangularMatrix"))
212                data <- as(data, "triangularMatrix")
213            else if(isSym && !is(data, "symmetricMatrix"))
214                data <- as(data, "symmetricMatrix")
215        }
216        ## now coerce in any case .. maybe producing sensible error message:
217      as(data, cl)      as(data, cl)
218  }  }
219
# Line 157  Line 224
224
225  setMethod("%*%", signature(x = "Matrix", y = "numeric"),  setMethod("%*%", signature(x = "Matrix", y = "numeric"),
226            function(x, y) callGeneric(x, as.matrix(y)))            function(x, y) callGeneric(x, as.matrix(y)))

227  setMethod("%*%", signature(x = "numeric", y = "Matrix"),  setMethod("%*%", signature(x = "numeric", y = "Matrix"),
228            function(x, y) callGeneric(rbind(x), y))            function(x, y) callGeneric(matrix(x, nrow = 1, byrow=TRUE), y))
229
230    setMethod("%*%", signature(x = "Matrix", y = "matrix"),
231              function(x, y) callGeneric(x, Matrix(y)))
232    setMethod("%*%", signature(x = "matrix", y = "Matrix"),
233              function(x, y) callGeneric(Matrix(x), y))
234
235
236  setMethod("crossprod", signature(x = "Matrix", y = "numeric"),  setMethod("crossprod", signature(x = "Matrix", y = "numeric"),
237            function(x, y = NULL) callGeneric(x, as.matrix(y)))            function(x, y = NULL) callGeneric(x, as.matrix(y)))

238  setMethod("crossprod", signature(x = "numeric", y = "Matrix"),  setMethod("crossprod", signature(x = "numeric", y = "Matrix"),
239            function(x, y = NULL)  callGeneric(rbind(x), y))            function(x, y = NULL)  callGeneric(as.matrix(x), y))
240
241    setMethod("crossprod", signature(x = "Matrix", y = "matrix"),
242              function(x, y = NULL) callGeneric(x, Matrix(y)))
243    setMethod("crossprod", signature(x = "matrix", y = "Matrix"),
244              function(x, y = NULL) callGeneric(Matrix(x), y))
245
246    ## The as.matrix() promotion seems illogical to MM,
247    ## but is according to help(tcrossprod, package = "base") :
248    setMethod("tcrossprod", signature(x = "Matrix", y = "numeric"),
249              function(x, y = NULL) callGeneric(x, as.matrix(y)))
250    setMethod("tcrossprod", signature(x = "numeric", y = "Matrix"),
251              function(x, y = NULL)  callGeneric(as.matrix(x), y))
252    setMethod("tcrossprod", signature(x = "Matrix", y = "matrix"),
253              function(x, y = NULL) callGeneric(x, Matrix(y)))
254    setMethod("tcrossprod", signature(x = "matrix", y = "Matrix"),
255              function(x, y = NULL) callGeneric(Matrix(x), y))
256
257    ## maybe not 100% optimal, but elegant:
258    setMethod("solve", signature(a = "Matrix", b = "missing"),
259              function(a, b, ...) solve(a, Diagonal(nrow(a))))
260
261  setMethod("solve", signature(a = "Matrix", b = "numeric"),  setMethod("solve", signature(a = "Matrix", b = "numeric"),
262            function(a, b, ...) callGeneric(a, as.matrix(b)))            function(a, b, ...) callGeneric(a, Matrix(b)))
263    setMethod("solve", signature(a = "Matrix", b = "matrix"),
264              function(a, b, ...) callGeneric(a, Matrix(b)))
265    setMethod("solve", signature(a = "matrix", b = "Matrix"),
266              function(a, b, ...) callGeneric(Matrix(a), b))
267
268    ## when no sub-class method is found, bail out
269    setMethod("solve", signature(a = "Matrix", b = "Matrix"),
270              function(a, b, ...) .bail.out.2("solve", class(a), class(b)))
271
272  ## bail-out methods in order to get better error messages  ## bail-out methods in order to get better error messages
273  setMethod("%*%", signature(x = "Matrix", y = "Matrix"),  setMethod("%*%", signature(x = "Matrix", y = "Matrix"),
# Line 180  Line 279
279            function (x, y = NULL) .bail.out.2(.Generic, class(x), class(y)))            function (x, y = NULL) .bail.out.2(.Generic, class(x), class(y)))
280  setMethod("crossprod", signature(x = "ANY", y = "Matrix"),  setMethod("crossprod", signature(x = "ANY", y = "Matrix"),
281            function (x, y = NULL) .bail.out.2(.Generic, class(x), class(y)))            function (x, y = NULL) .bail.out.2(.Generic, class(x), class(y)))
282    setMethod("tcrossprod", signature(x = "Matrix", y = "ANY"),
283              function (x, y = NULL) .bail.out.2(.Generic, class(x), class(y)))
284    setMethod("tcrossprod", signature(x = "ANY", y = "Matrix"),
285              function (x, y = NULL) .bail.out.2(.Generic, class(x), class(y)))
286
287    ## cheap fallbacks
288    setMethod("crossprod", signature(x = "Matrix", y = "Matrix"),
289              function(x, y = NULL) t(x) %*% y)
290    setMethod("tcrossprod", signature(x = "Matrix", y = "Matrix"),
291              function(x, y = NULL) x %*% t(y))
292
293  ## There are special sparse methods; this is a "fall back":  ## There are special sparse methods; this is a "fall back":
294  setMethod("kronecker", signature(X = "Matrix", Y = "ANY",  setMethod("kronecker", signature(X = "Matrix", Y = "ANY",
295                                   FUN = "ANY", make.dimnames = "ANY"),                                   FUN = "ANY", make.dimnames = "ANY"),
296            function(X, Y, FUN, make.dimnames, ...) {            function(X, Y, FUN, make.dimnames, ...) {
297                  if(is(X, "sparseMatrix"))
298                      warning("using slow kronecker() method")
299                X <- as(X, "matrix") ; Matrix(callGeneric()) })                X <- as(X, "matrix") ; Matrix(callGeneric()) })
300
301  setMethod("kronecker", signature(X = "ANY", Y = "Matrix",  setMethod("kronecker", signature(X = "ANY", Y = "Matrix",
302                                   FUN = "ANY", make.dimnames = "ANY"),                                   FUN = "ANY", make.dimnames = "ANY"),
303            function(X, Y, FUN, make.dimnames, ...) {            function(X, Y, FUN, make.dimnames, ...) {
304                  if(is(Y, "sparseMatrix"))
305                      warning("using slow kronecker() method")
306                Y <- as(Y, "matrix") ; Matrix(callGeneric()) })                Y <- as(Y, "matrix") ; Matrix(callGeneric()) })
307
308
309    ## FIXME: All of these should never be called
310    setMethod("chol", signature(x = "Matrix"),
311              function(x, pivot = FALSE) .bail.out.1(.Generic, class(x)))
312    setMethod("determinant", signature(x = "Matrix"),
313              function(x, logarithm = TRUE) .bail.out.1(.Generic, class(x)))
314
315    setMethod("diag", signature(x = "Matrix"),
316              function(x, nrow, ncol) .bail.out.1(.Generic, class(x)))
317  setMethod("t", signature(x = "Matrix"),  setMethod("t", signature(x = "Matrix"),
318            function(x) .bail.out.1(.Generic, class(x)))            function(x) .bail.out.1(.Generic, class(x)))
319
320  ## Group Methods  setMethod("norm", signature(x = "Matrix", type = "character"),
321  setMethod("+", signature(e1 = "Matrix", e2 = "missing"), function(e1) e1)            function(x, type, ...) .bail.out.1(.Generic, class(x)))
322  ## "fallback":  setMethod("rcond", signature(x = "Matrix", type = "character"),
323  setMethod("-", signature(e1 = "Matrix", e2 = "missing"),            function(x, type, ...) .bail.out.1(.Generic, class(x)))
324            function(e1) {
325                warning("inefficient method used for \"- e1\"")
326                0-e1  ## for all :
327    setMethod("norm", signature(x = "ANY", type = "missing"),
328              function(x, type, ...) norm(x, type = "O", ...))
329    setMethod("rcond", signature(x = "ANY", type = "missing"),
330              function(x, type, ...) rcond(x, type = "O", ...))
331
332
333
334
335
336    ## MM: More or less "Cut & paste" from
337    ## --- diff.default() from  R/src/library/base/R/diff.R :
338    setMethod("diff", signature(x = "Matrix"),
339              function(x, lag = 1, differences = 1, ...) {
340                  if (length(lag) > 1 || length(differences) > 1 ||
341                      lag < 1 || differences < 1)
342                      stop("'lag' and 'differences' must be integers >= 1")
343                  xlen <- nrow(x)
344                  if (lag * differences >= xlen)
345                      return(x[,FALSE][0])  # empty of proper mode
346
347                  i1 <- -1:-lag
348                  for (i in 1:differences)
349                      x <- x[i1, , drop = FALSE] -
350                          x[-nrow(x):-(nrow(x)-lag+1), , drop = FALSE]
351                  x
352            })            })
353
354  ## bail-outs:  setMethod("image", "Matrix",
355  setMethod("Compare", signature(e1 = "Matrix", e2 = "Matrix"),            function(x, ...) { # coercing to sparse is not inefficient,
356            function(e1, e2) {                ##               since we need 'i' and 'j' for levelplot()
357                d <- dimCheck(e1,e2)                x <- as(as(x, "sparseMatrix"), "dMatrix")
358                .bail.out.2(.Generic, class(e1), class(e2))                callGeneric()
359            })            })
setMethod("Compare", signature(e1 = "Matrix", e2 = "ANY"),
function(e1, e2) .bail.out.2(.Generic, class(e1), class(e2)))
setMethod("Compare", signature(e1 = "ANY", e2 = "Matrix"),
function(e1, e2) .bail.out.2(.Generic, class(e1), class(e2)))
360
361
362    ## Group Methods
363
364    ##-> see ./Ops.R
365    ##         ~~~~~
366    ## For all  non-dMatrix objects, and note that  "all" and "any" have their own
367    setMethod("Summary", signature(x = "Matrix", na.rm = "ANY"),
368              function(x, ..., na.rm)
369              callGeneric(as(x,"dMatrix"), ..., na.rm = na.rm))
370
371
372  ### --------------------------------------------------------------------------  ### --------------------------------------------------------------------------
373  ###  ###
# Line 228  Line 380
380  ## "x[]":  ## "x[]":
381  setMethod("[", signature(x = "Matrix",  setMethod("[", signature(x = "Matrix",
382                           i = "missing", j = "missing", drop = "ANY"),                           i = "missing", j = "missing", drop = "ANY"),
383            function (x, i, j, drop) x)            function (x, i, j, ..., drop) x)
384
385  ## missing 'drop' --> 'drop = TRUE'  ## missing 'drop' --> 'drop = TRUE'
386  ##                     -----------  ##                     -----------
387  ## select rows  ## select rows __ or __ vector indexing:
388  setMethod("[", signature(x = "Matrix", i = "index", j = "missing",  setMethod("[", signature(x = "Matrix", i = "index", j = "missing",
389                           drop = "missing"),                           drop = "missing"),
390            function(x,i,j, drop) callGeneric(x, i=i, drop= TRUE))            function(x,i,j, ..., drop) {
391                  if(nargs() == 2) { ## e.g. M[0] , M[TRUE],  M[1:2]
392                      if(any(as.logical(i)) || prod(dim(x)) == 0)
393                          ## FIXME: for *large sparse*, use sparseVector !
394                          as.vector(x)[i]
395                      else ## save memory (for large sparse M):
396                          as.vector(x[1,1])[FALSE]
397                  } else {
398                      callGeneric(x, i=i, , drop=TRUE)
399                      ##                  ^^
400                  }
401              })
402
403  ## select columns  ## select columns
404  setMethod("[", signature(x = "Matrix", i = "missing", j = "index",  setMethod("[", signature(x = "Matrix", i = "missing", j = "index",
405                           drop = "missing"),                           drop = "missing"),
406            function(x,i,j, drop) callGeneric(x, j=j, drop= TRUE))            function(x,i,j, ..., drop) callGeneric(x, j=j, drop= TRUE))
407  setMethod("[", signature(x = "Matrix", i = "index", j = "index",  setMethod("[", signature(x = "Matrix", i = "index", j = "index",
408                           drop = "missing"),                           drop = "missing"),
409            function(x,i,j, drop) callGeneric(x, i=i, j=j, drop= TRUE))            function(x,i,j, ..., drop) callGeneric(x, i=i, j=j, drop= TRUE))
410
411  ## bail out if any of (i,j,drop) is "non-sense"  ## bail out if any of (i,j,drop) is "non-sense"
412  setMethod("[", signature(x = "Matrix", i = "ANY", j = "ANY", drop = "ANY"),  setMethod("[", signature(x = "Matrix", i = "ANY", j = "ANY", drop = "ANY"),
413            function(x,i,j, drop)            function(x,i,j, ..., drop)
414            stop("invalid or not-yet-implemented 'Matrix' subsetting"))            stop("invalid or not-yet-implemented 'Matrix' subsetting"))
415
416  ##  "logical *vector* indexing, such as  M [ M >= 10 ] :  ## logical indexing, such as M[ M >= 7 ] *BUT* also M[ M[,1] >= 3,],
417    ## The following is *both* for    M [ <logical>   ]
418    ##                 and also for   M [ <logical> , ]
419    .M.sub.i.logical <- function (x, i, j, ..., drop)
420    {
421        nA <- nargs()
422        if(nA == 2) { ##  M [ M >= 7 ]
423            ## FIXME: when both 'x' and 'i' are sparse, this can be very inefficient
424            if(is(x, "sparseMatrix"))
425                message("<sparse>[ <logic> ] : .M.sub.i.logical() maybe inefficient")
426            toC <- geClass(x)
427            if(canCoerce(x, toC)) as(x, toC)@x[as.vector(i)]
428            else as(as(as(x, "generalMatrix"), "denseMatrix"), toC)@x[as.vector(i)]
429            ## -> error when lengths don't match
430        } else if(nA == 3) { ##  M [ M[,1, drop=FALSE] >= 7, ]
431            stop("not-yet-implemented 'Matrix' subsetting") ## FIXME
432
433        } else stop("nargs() = ", nA,
434                    ".  Extraneous illegal arguments inside '[ .. ]' (i.logical)?")
435    }
436  setMethod("[", signature(x = "Matrix", i = "lMatrix", j = "missing",  setMethod("[", signature(x = "Matrix", i = "lMatrix", j = "missing",
437                           drop = "ANY"),                           drop = "ANY"),
438            function (x, i, j, drop) {            .M.sub.i.logical)
as(x, geClass(x))@x[as.vector(i)]
# -> error when lengths don't match
})

439  setMethod("[", signature(x = "Matrix", i = "logical", j = "missing",  setMethod("[", signature(x = "Matrix", i = "logical", j = "missing",
440                           drop = "ANY"),                           drop = "ANY"),
441            function (x, i, j, drop) as(x, geClass(x))@x[i])            .M.sub.i.logical)
442
443
444    subset.ij <- function(x, ij) {
445        m <- nrow(ij)
446        if(m > 3) {
447            cld <- getClassDef(class(x))
448            sym.x <- extends(cld, "symmetricMatrix")
449            if(sym.x) {
450                W <- if(x@uplo == "U") # stored only [i,j] with i <= j
451                    ij[,1] > ij[,2] else ij[,1] < ij[,2]
452                if(any(W))
453                    ij[W,] <- ij[W, 2:1]
454            }
455            if(extends(cld, "sparseMatrix")) {
456                ## do something smarter:
457                nr <- nrow(x)
458                if(!extends(cld, "CsparseMatrix")) {
459                    x <- as(x, "CsparseMatrix") # simpler; our standard
460                    cld <- getClassDef(class(x))
461                }
462                tri.x <- extends(cld, "triangularMatrix")
463                if(tri.x) {
464                    ## need these for the 'x' slot in any case
465                    if (x@diag == "U") x <- .Call(Csparse_diagU2N, x)
466                    ## slightly more efficient than non0.i() or non0ind():
467                    ij.x <- .Call(compressed_non_0_ij, x, isC=TRUE)
468                } else { ## symmetric / general : for symmetric, only "existing"b
469                    ij.x <- non0.i(x, cld)
470                }
471
472                mi <- match(encodeInd(ij.x,   nr),
473                            encodeInd(ij -1L, nr), nomatch=0)
474                mmi <- mi != 0
475                ## Result:
476                ans <- vector(mode = .type.kind[.M.kindC(cld)], length = m)
477                ## those that are *not* zero:
478                ans[mi[mmi]] <-
479                    if(extends(cld, "nsparseMatrix")) TRUE else x@x[mmi]
480                ans
481
482            } else { ## non-sparse : dense
483                message("m[ <ij-matrix> ]: inefficiently indexing single elements")
484                i1 <- ij[,1]
485                i2 <- ij[,2]
486                ## very inefficient for large m -- FIXME! --
487                unlist(lapply(seq_len(m), function(j) x[i1[j], i2[j]]))
488            }
489        } else { # 1 <= m <= 3
490            i1 <- ij[,1]
491            i2 <- ij[,2]
492            unlist(lapply(seq_len(m), function(j) x[i1[j], i2[j]]))
493        }
494    }
495
496    ## A[ ij ]  where ij is (i,j) 2-column matrix -- but also when that is logical mat!
497    .M.sub.i.2col <- function (x, i, j, ..., drop)
498    {
499        nA <- nargs()
500        if(nA == 2) { ##  M [ cbind(ii,jj) ] or M [ <logical matrix> ]
501            if(!is.integer(nc <- ncol(i)))
502                stop(".M.sub.i.2col(): 'i' has no integer column number;\n",
503                     "should never happen; please report")
504            if(is.logical(i))
505                return(.M.sub.i.logical(x, i=i)) # call with 2 args!
506            else if(!is.numeric(i) || nc != 2)
507                stop("such indexing must be by logical or 2-column numeric matrix")
508            m <- nrow(i)
509            if(m == 0) return(vector(mode = .type.kind[.M.kind(x)]))
510            ## else
511            subset.ij(x, i)
512
513  ## "FIXME:"      } else stop("nargs() = ", nA,
514  ## How can we get at   A[ ij ]  where ij is (i,j) 2-column matrix?                  ".  Extraneous illegal arguments inside '[ .. ]' (i.2col)?")
515  ##  and                A[ LL ]  where LL is a logical *vector*  }
516  ## -> [.data.frame uses nargs() - can we do this in the *generic* ?  setMethod("[", signature(x = "Matrix", i = "matrix", j = "missing"),# drop="ANY"
517              .M.sub.i.2col)
518
519
520  ### "[<-" : -----------------  ### "[<-" : -----------------
# Line 274  Line 523
523  setReplaceMethod("[", signature(x = "Matrix", i = "missing", j = "missing",  setReplaceMethod("[", signature(x = "Matrix", i = "missing", j = "missing",
524                                  value = "ANY"),## double/logical/...                                  value = "ANY"),## double/logical/...
525            function (x, value) {            function (x, value) {
526                x@x <- value                ## Fails for 'nMatrix' ... FIXME : make sure have method there
527                  x@x <- rep(value, length = length(x@x))
528                validObject(x)# check if type and lengths above match                validObject(x)# check if type and lengths above match
529                x                x
530            })            })
531
532  ## Method for all 'Matrix' kinds (rather than incomprehensible error messages);  ## A[ ij ] <- value,  where ij is (i,j) 2-column matrix :
533    ## ----------------
534    ## The cheap general method --- FIXME: provide special ones; done for Tsparse..
535    ## NOTE:  need '...' below such that setMethod() does
536    ##        not use .local() such that nargs() will work correctly:
537    .M.repl.i.2col <- function (x, i, j, ..., value)
538    {
539        nA <- nargs()
540        if(nA == 3) { ##  M [ cbind(ii,jj) ] <- value  or M [ Lmat ] <- value
541            if(!is.integer(nc <- ncol(i)))
542                stop(".M.repl.i.2col(): 'i' has no integer column number;\n",
543                     "should never happen; please report")
544            else if(!is.numeric(i) || nc != 2)
545                stop("such indexing must be by logical or 2-column numeric matrix")
546            if(is.logical(i)) {
547                message(".M.repl.i.2col(): drop 'matrix' case ...")
548                ## c(i) : drop "matrix" to logical vector
549                return( callGeneric(x, i=c(i), value=value) )
550            }
551            if(!is.integer(i)) storage.mode(i) <- "integer"
552            if(any(i < 0))
553                stop("negative values are not allowed in a matrix subscript")
554            if(any(is.na(i)))
555                stop("NAs are not allowed in subscripted assignments")
556            if(any(i0 <- (i == 0))) # remove them
557                i <- i[ - which(i0, arr.ind = TRUE)[,"row"], ]
558            ## now have integer i >= 1
559            m <- nrow(i)
560            ## mod.x <- .type.kind[.M.kind(x)]
561            if(length(value) > 0 && m %% length(value) != 0)
562                warning("number of items to replace is not a multiple of replacement length")
563            ## recycle:
564            value <- rep(value, length = m)
565            i1 <- i[,1]
566            i2 <- i[,2]
567            if(m > 2)
568                message("m[ <ij-matrix> ] <- v: inefficiently treating single elements")
569            ## inefficient -- FIXME -- (also loses "symmetry" unnecessarily)
570            for(k in seq_len(m))
571                x[i1[k], i2[k]] <- value[k]
572
573            x
574        } else stop("nargs() = ", nA,
575                    ".  Extraneous illegal arguments inside '[ .. ]' ?")
576    }
577
578    setReplaceMethod("[", signature(x = "Matrix", i = "matrix", j = "missing",
579                                    value = "replValue"),
580              .M.repl.i.2col)
581
582
583    setReplaceMethod("[", signature(x = "Matrix", i = "missing", j = "ANY",
584                                    value = "Matrix"),
585                     function (x, i, j, ..., value)
586                     callGeneric(x=x, , j=j, value = as.vector(value)))
587
588    setReplaceMethod("[", signature(x = "Matrix", i = "ANY", j = "missing",
589                                    value = "Matrix"),
590                     function (x, i, j, ..., value)
591                     callGeneric(x=x, i=i, , value = as.vector(value)))
592
593    setReplaceMethod("[", signature(x = "Matrix", i = "ANY", j = "ANY",
594                                    value = "Matrix"),
595                     function (x, i, j, ..., value)
596                     callGeneric(x=x, i=i, j=j, value = as.vector(value)))
597
598    setReplaceMethod("[", signature(x = "Matrix", i = "missing", j = "ANY",
599                                    value = "matrix"),
600                     function (x, i, j, ..., value)
601                     callGeneric(x=x, , j=j, value = c(value)))
602
603    setReplaceMethod("[", signature(x = "Matrix", i = "ANY", j = "missing",
604                                    value = "matrix"),
605                     function (x, i, j, ..., value)
606                     callGeneric(x=x, i=i, , value = c(value)))
607
608    setReplaceMethod("[", signature(x = "Matrix", i = "ANY", j = "ANY",
609                                    value = "matrix"),
610                     function (x, i, j, value)
611                     callGeneric(x=x, i=i, j=j, value = c(value)))
612
613  ## (ANY,ANY,ANY) is used when no `real method' is implemented :  ## (ANY,ANY,ANY) is used when no `real method' is implemented :
614  setReplaceMethod("[", signature(x = "Matrix", i = "ANY", j = "ANY",  setReplaceMethod("[", signature(x = "Matrix", i = "ANY", j = "ANY",
615                                  value = "ANY"),                                  value = "ANY"),
616            function (x, i, j, value) {            function (x, i, j, value) {
617                if(!is.atomic(value))                if(!is.atomic(value))
618                    stop("RHS 'value' must match matrix class ", class(x))                    stop(sprintf("RHS 'value' (class %s) matches 'ANY', but must match matrix class %s",
619                                   class(value),class(x)))
620                else stop("not-yet-implemented 'Matrix[<-' method")                else stop("not-yet-implemented 'Matrix[<-' method")
621            })            })

## The trivial methods :
setMethod("cbind2", signature(x = "Matrix", y = "NULL"),
function(x, y) x)
setMethod("cbind2", signature(x = "Matrix", y = "missing"),
function(x, y) x)
setMethod("cbind2", signature(x = "NULL", y="Matrix"),
function(x, y) x)

setMethod("rbind2", signature(x = "Matrix", y = "NULL"),
function(x, y) x)
setMethod("rbind2", signature(x = "Matrix", y = "missing"),
function(x, y) x)
setMethod("rbind2", signature(x = "NULL", y="Matrix"),
function(x, y) x)

## Makes sure one gets x decent error message for the unimplemented cases:
setMethod("cbind2", signature(x = "Matrix", y = "Matrix"),
function(x, y) {
rowCheck(x,y)
stop(gettextf("cbind2() method for (%s,%s) not-yet defined",
class(x), class(y)))
})

## Use a working fall back {particularly useful for sparse}:
## FIXME: implement rbind2 via "cholmod" for C* and Tsparse ones
setMethod("rbind2", signature(x = "Matrix", y = "Matrix"),
function(x, y) {
colCheck(x,y)
t(cbind2(t(x), t(y)))
})

Legend:
 Removed from v.1290 changed lines Added in v.2112