# SCM Repository

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

# Diff of /pkg/R/Matrix.R

revision 1673, Mon Nov 6 20:54:26 2006 UTC revision 2112, Mon Feb 18 08:24:46 2008 UTC
# Line 3  Line 3
3
4  ### Virtual coercions -- via smart "helpers" (-> ./Auxiliaries.R)  ### Virtual coercions -- via smart "helpers" (-> ./Auxiliaries.R)
5
6  setAs("Matrix", "sparseMatrix", function(from) as_Csparse(from))  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))  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:  ## Most of these work; this is a last resort:
14  setAs(from = "Matrix", to = "matrix", # do *not* call base::as.matrix() here:  setAs(from = "Matrix", to = "matrix", # do *not* call base::as.matrix() here:
15        function(from) .bail.out.2("coerce", class(from), class(to)))        function(from) .bail.out.2("coerce", class(from), class(to)))
# Line 27  Line 31
32  setMethod("tail", signature(x = "Matrix"), utils::tail.matrix)  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")))
# Line 37  Line 44
44  setMethod("as.logical", signature(x = "Matrix"),  setMethod("as.logical", signature(x = "Matrix"),
45            function(x, ...) as.logical(as.vector(x)))            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  ## "base" has an isSymmetric() S3-generic since R 2.3.0  ## "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))

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, forceCheck = FALSE)                sparse = NULL, forceCheck = FALSE)
# Line 82  Line 116
116      sparseDefault <- function(m) prod(dim(m)) > 2*sum(isN0(as(m, "matrix")))      sparseDefault <- function(m) prod(dim(m)) > 2*sum(isN0(as(m, "matrix")))
117
118      i.M <- is(data, "Matrix")      i.M <- is(data, "Matrix")
119        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")))      if(is.null(sparse1 <- sparse) && (i.M || is(data, "matrix")))
122          sparse <- sparseDefault(data)          sparse <- sparseDefault(data)
123
124      doDN <- TRUE      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(!forceCheck && ((sparse && sM) || (!sparse && !sM)))          if(!forceCheck && ((sparse && sM) || (!sparse && !sM)))
130              return(data)              return(data)
# Line 101  Line 138
138          if(length(data) == 1 && is0(data) && !identical(sparse, FALSE)) {          if(length(data) == 1 && is0(data) && !identical(sparse, FALSE)) {
139              ## Matrix(0, ...) : always sparse unless "sparse = FALSE":              ## Matrix(0, ...) : always sparse unless "sparse = FALSE":
140              if(is.null(sparse)) sparse1 <- sparse <- TRUE              if(is.null(sparse)) sparse1 <- sparse <- TRUE
141                i.M <- sM <- TRUE
142              ## will be sparse: do NOT construct full matrix!              ## will be sparse: do NOT construct full matrix!
143              data <- new(if(is.numeric(data)) "dgTMatrix" else              data <- new(if(is.numeric(data)) "dgTMatrix" else
144                          if(is.logical(data)) "lgTMatrix" else                          if(is.logical(data)) "lgTMatrix" else
# Line 108  Line 146
146                          Dim = as.integer(c(nrow,ncol)),                          Dim = as.integer(c(nrow,ncol)),
147                          Dimnames = if(is.null(dimnames)) list(NULL,NULL)                          Dimnames = if(is.null(dimnames)) list(NULL,NULL)
148                          else dimnames)                          else dimnames)
149          } else { ## normal case          } 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)
dimnames(data) <- dimnames
158          }          }
159          doDN <- FALSE          doDN <- FALSE
160      }      } 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))      if (doDN && !is.null(dimnames))
165          dimnames(data) <- dimnames          dimnames(data) <- dimnames
# Line 158  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 169  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(matrix(x, nrow = 1, byrow=TRUE), 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(as.matrix(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,  ## The as.matrix() promotion seems illogical to MM,
247  ## but is according to help(tcrossprod, package = "base") :  ## but is according to help(tcrossprod, package = "base") :
248  setMethod("tcrossprod", signature(x = "Matrix", y = "numeric"),  setMethod("tcrossprod", signature(x = "Matrix", y = "numeric"),
249            function(x, y = NULL) callGeneric(x, as.matrix(y)))            function(x, y = NULL) callGeneric(x, as.matrix(y)))
250  setMethod("tcrossprod", signature(x = "numeric", y = "Matrix"),  setMethod("tcrossprod", signature(x = "numeric", y = "Matrix"),
251            function(x, y = NULL)  callGeneric(as.matrix(x), y))            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 optimal  ## maybe not 100% optimal, but elegant:
258  setMethod("solve", signature(a = "Matrix", b = "missing"),  setMethod("solve", signature(a = "Matrix", b = "missing"),
259            function(a, b, ...) solve(a, Diagonal(nrow(a))))            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)))
## when no sub-class method is found, bail out
263  setMethod("solve", signature(a = "Matrix", b = "matrix"),  setMethod("solve", signature(a = "Matrix", b = "matrix"),
264            function(a, b, ...) .bail.out.2("solve", class(a), "matrix"))            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 220  Line 294
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
# Line 238  Line 317
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  ## old-style matrices are made into new ones  setMethod("image", "Matrix",
355  setMethod("Ops", signature(e1 = "Matrix", e2 = "matrix"),            function(x, ...) { # coercing to sparse is not inefficient,
356            function(e1, e2) callGeneric(e1, Matrix(e2)))                ##               since we need 'i' and 'j' for levelplot()
357  ##          callGeneric(e1, Matrix(e2, sparse=is(e1,"sparseMatrix"))))                x <- as(as(x, "sparseMatrix"), "dMatrix")
358  setMethod("Ops", signature(e1 = "matrix", e2 = "Matrix"),                callGeneric()
function(e1, e2) callGeneric(Matrix(e1), e2))

## bail-outs -- on highest possible level, hence "Ops", not "Compare"/"Arith" :
setMethod("Ops", signature(e1 = "Matrix", e2 = "Matrix"),
function(e1, e2) {
d <- dimCheck(e1,e2)
.bail.out.2(.Generic, class(e1), class(e2))
359            })            })
setMethod("Ops", signature(e1 = "Matrix", e2 = "ANY"),
function(e1, e2) .bail.out.2(.Generic, class(e1), class(e2)))
setMethod("Ops", 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 278  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 indexing, such as M[ M >= 7 ] *BUT* also M[ M[,1] >= 3,],  ## logical indexing, such as M[ M >= 7 ] *BUT* also M[ M[,1] >= 3,],
417  ## The following is *both* for    M [ <logical>   ]  ## The following is *both* for    M [ <logical>   ]
418  ##                 and also for   M [ <logical> , ]  ##                 and also for   M [ <logical> , ]
419  .M.sub.i.logical <- function (x, i, j, drop)  .M.sub.i.logical <- function (x, i, j, ..., drop)
420  {  {
421      nA <- nargs()      nA <- nargs()
422      if(nA == 2) { ##  M [ M >= 7 ]      if(nA == 2) { ##  M [ M >= 7 ]
423          ## FIXME: when both 'x' and 'i' are sparse, this can be very inefficient          ## FIXME: when both 'x' and 'i' are sparse, this can be very inefficient
424          as(x, geClass(x))@x[as.vector(i)]          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          ## -> error when lengths don't match
430      } else if(nA == 3) { ##  M [ M[,1, drop=FALSE] >= 7, ]      } else if(nA == 3) { ##  M [ M[,1, drop=FALSE] >= 7, ]
431          stop("not-yet-implemented 'Matrix' subsetting") ## FIXME          stop("not-yet-implemented 'Matrix' subsetting") ## FIXME
432
433      } else stop("nargs() = ", nA,      } else stop("nargs() = ", nA,
434                  " should never happen; please report.")                  ".  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"),
# Line 323  Line 441
441            .M.sub.i.logical)            .M.sub.i.logical)
442
443
444  ## A[ ij ]  where ij is (i,j) 2-column matrix :  subset.ij <- function(x, ij) {
445  .M.sub.i.2col <- function (x, i, j, drop)      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()      nA <- nargs()
500      if(nA == 2) { ##  M [ cbind(ii,jj) ]      if(nA == 2) { ##  M [ cbind(ii,jj) ] or M [ <logical matrix> ]
501          if(!is.integer(nc <- ncol(i)))          if(!is.integer(nc <- ncol(i)))
502              stop("'i' has no integer column number",              stop(".M.sub.i.2col(): 'i' has no integer column number;\n",
503                   " should never happen; please report")                   " should never happen; please report")
504          if(is.logical(i))          if(is.logical(i))
505              return(.M.sub.i.logical(x,i,j,drop))              return(.M.sub.i.logical(x, i=i)) # call with 2 args!
506          else if(!is.numeric(i) || nc != 2)          else if(!is.numeric(i) || nc != 2)
507              stop("such indexing must be by logical or 2-column numeric matrix")              stop("such indexing must be by logical or 2-column numeric matrix")
508          m <- nrow(i)          m <- nrow(i)
509          if(m == 0) return(vector(mode = .type.kind[.M.kind(x)]))          if(m == 0) return(vector(mode = .type.kind[.M.kind(x)]))
510          ## else          ## else
511          i1 <- i[,1]          subset.ij(x, i)
i2 <- i[,2]
## potentially inefficient -- FIXME --
unlist(lapply(seq_len(m), function(j) x[i1[j], i2[j]]))
512
513      } else stop("nargs() = ", nA, " should never happen; please report.")      } else stop("nargs() = ", nA,
514                    ".  Extraneous illegal arguments inside '[ .. ]' (i.2col)?")
515  }  }
516  setMethod("[", signature(x = "Matrix", i = "matrix", j = "missing"),# drop="ANY"  setMethod("[", signature(x = "Matrix", i = "matrix", j = "missing"),# drop="ANY"
517            .M.sub.i.2col)            .M.sub.i.2col)
# Line 356  Line 524
524                                  value = "ANY"),## double/logical/...                                  value = "ANY"),## double/logical/...
525            function (x, value) {            function (x, value) {
526                ## Fails for 'nMatrix' ... FIXME : make sure have method there                ## Fails for 'nMatrix' ... FIXME : make sure have method there
527                x@x <- value                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  ## A[ ij ] <- value,  where ij is (i,j) 2-column matrix :  ## A[ ij ] <- value,  where ij is (i,j) 2-column matrix :
533  .M.repl.i.2col <- function (x, i, j, value)  ## ----------------
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()      nA <- nargs()
540      if(nA == 3) { ##  M [ cbind(ii,jj) ] <- value      if(nA == 3) { ##  M [ cbind(ii,jj) ] <- value  or M [ Lmat ] <- value
541          if(!is.integer(nc <- ncol(i)))          if(!is.integer(nc <- ncol(i)))
542              stop("'i' has no integer column number",              stop(".M.repl.i.2col(): 'i' has no integer column number;\n",
543                   " should never happen; please report")                   " should never happen; please report")
544          if(is.logical(i)) {          else if(!is.numeric(i) || nc != 2)
i <- c(i) # drop "matrix"
return( callNextMethod() )
} else if(!is.numeric(i) || nc != 2)
545              stop("such indexing must be by logical or 2-column numeric matrix")              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)          m <- nrow(i)
560          mod.x <- .type.kind[.M.kind(x)]          ## mod.x <- .type.kind[.M.kind(x)]
561          if(length(value) > 0 && m %% length(value) != 0)          if(length(value) > 0 && m %% length(value) != 0)
562              warning("number of items to replace is not a multiple of replacement length")              warning("number of items to replace is not a multiple of replacement length")
563          ## recycle:          ## recycle:
564          value <- rep(value, length = m)          value <- rep(value, length = m)
565          i1 <- i[,1]          i1 <- i[,1]
566          i2 <- i[,2]          i2 <- i[,2]
567            if(m > 2)
568                message("m[ <ij-matrix> ] <- v: inefficiently treating single elements")
569          ## inefficient -- FIXME -- (also loses "symmetry" unnecessarily)          ## inefficient -- FIXME -- (also loses "symmetry" unnecessarily)
570          for(k in seq_len(m))          for(k in seq_len(m))
571              x[i1[k], i2[k]] <- value[k]              x[i1[k], i2[k]] <- value[k]
x
572
573      } else stop("nargs() = ", nA, " should never happen; please report.")          x
574        } else stop("nargs() = ", nA,
575                    ".  Extraneous illegal arguments inside '[ .. ]' ?")
576  }  }
577
578  setReplaceMethod("[", signature(x = "Matrix", i = "matrix", j = "missing",  setReplaceMethod("[", signature(x = "Matrix", i = "matrix", j = "missing",
579                                  value = "replValue"),                                  value = "replValue"),
580            .M.repl.i.2col)            .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",  setReplaceMethod("[", signature(x = "Matrix", i = "ANY", j = "ANY",
594                                  value = "Matrix"),                                  value = "Matrix"),
595                   function (x, i, j, value)                   function (x, i, j, ..., value)
596                   callGeneric(x=x, i=i, j=j, value = as.vector(value)))                   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",  setReplaceMethod("[", signature(x = "Matrix", i = "ANY", j = "ANY",
609                                  value = "matrix"),                                  value = "matrix"),
610                   function (x, i, j, value)                   function (x, i, j, value)
# Line 412  Line 619
619                                 class(value),class(x)))                                 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.1673 changed lines Added in v.2112