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 2081, Sat Oct 6 22:01:45 2007 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 56  Line 63
63
64  setMethod("dim", signature(x = "Matrix"),  setMethod("dim", signature(x = "Matrix"),
65            function(x) x@Dim, valueClass = "integer")            function(x) x@Dim, valueClass = "integer")
66
67    setMethod("length", "Matrix", function(x) prod(dim(x)))
68
69  setMethod("dimnames", signature(x = "Matrix"), function(x) x@Dimnames)  setMethod("dimnames", signature(x = "Matrix"), function(x) x@Dimnames)
70
71
72  ## not exported but used more than once for "dimnames<-" method :  ## not exported but used more than once for "dimnames<-" method :
73  ## -- or do only once for all "Matrix" classes ??  ## -- or do only once for all "Matrix" classes ??
74  dimnamesGets <- function (x, value) {  dimnamesGets <- function (x, value) {
# Line 75  Line 87
87  setMethod("unname", signature("Matrix", force="missing"),  setMethod("unname", signature("Matrix", force="missing"),
88            function(obj) { obj@Dimnames <- list(NULL,NULL); obj})            function(obj) { obj@Dimnames <- list(NULL,NULL); obj})
89
90    setMethod("all", signature(x = "Matrix"),
91              function(x, ..., na.rm)
92              callGeneric(as(x, "lMatrix"), ..., na.rm=na.rm))
93
94    setMethod("any", signature(x = "Matrix"),
95              function(x, ..., na.rm)
96              callGeneric(as(x, "lMatrix"), ..., na.rm=na.rm))
97
98    ## NOTE:  "&" and "|"  are now in group "Logic" c "Ops" --> ./Ops.R
99    ##        "!" is in ./not.R
100
101
102  Matrix <-  Matrix <-
103      function (data = NA, nrow = 1, ncol = 1, byrow = FALSE, dimnames = NULL,      function (data = NA, nrow = 1, ncol = 1, byrow = FALSE, dimnames = NULL,
104                sparse = NULL, forceCheck = FALSE)                sparse = NULL, forceCheck = FALSE)
# Line 82  Line 106
106      sparseDefault <- function(m) prod(dim(m)) > 2*sum(isN0(as(m, "matrix")))      sparseDefault <- function(m) prod(dim(m)) > 2*sum(isN0(as(m, "matrix")))
107
108      i.M <- is(data, "Matrix")      i.M <- is(data, "Matrix")
109        if(!i.M && inherits(data, "table")) # special treatment
110            class(data) <- "matrix" # "matrix" first for S4 dispatch
111      if(is.null(sparse1 <- sparse) && (i.M || is(data, "matrix")))      if(is.null(sparse1 <- sparse) && (i.M || is(data, "matrix")))
112          sparse <- sparseDefault(data)          sparse <- sparseDefault(data)
113
114      doDN <- TRUE      doDN <- TRUE
115      if (i.M) {      if (i.M) {
116            if(!missing(nrow) || !missing(ncol)|| !missing(byrow))
117                warning("'nrow', 'ncol', etc, are disregarded when 'data' is \"Matrix\" already")
118          sM <- is(data,"sparseMatrix")          sM <- is(data,"sparseMatrix")
119          if(!forceCheck && ((sparse && sM) || (!sparse && !sM)))          if(!forceCheck && ((sparse && sM) || (!sparse && !sM)))
120              return(data)              return(data)
# Line 101  Line 128
128          if(length(data) == 1 && is0(data) && !identical(sparse, FALSE)) {          if(length(data) == 1 && is0(data) && !identical(sparse, FALSE)) {
129              ## Matrix(0, ...) : always sparse unless "sparse = FALSE":              ## Matrix(0, ...) : always sparse unless "sparse = FALSE":
130              if(is.null(sparse)) sparse1 <- sparse <- TRUE              if(is.null(sparse)) sparse1 <- sparse <- TRUE
131                i.M <- sM <- TRUE
132              ## will be sparse: do NOT construct full matrix!              ## will be sparse: do NOT construct full matrix!
133              data <- new(if(is.numeric(data)) "dgTMatrix" else              data <- new(if(is.numeric(data)) "dgTMatrix" else
134                          if(is.logical(data)) "lgTMatrix" else                          if(is.logical(data)) "lgTMatrix" else
# Line 108  Line 136
136                          Dim = as.integer(c(nrow,ncol)),                          Dim = as.integer(c(nrow,ncol)),
137                          Dimnames = if(is.null(dimnames)) list(NULL,NULL)                          Dimnames = if(is.null(dimnames)) list(NULL,NULL)
138                          else dimnames)                          else dimnames)
139          } else { ## normal case          } else { ## normal case - using .Internal() to avoid more copying
140                if(getRversion() >= "2.7.0")
141                    data <- .Internal(matrix(data, nrow, ncol, byrow, dimnames))
142                else {
143              data <- .Internal(matrix(data, nrow, ncol, byrow))              data <- .Internal(matrix(data, nrow, ncol, byrow))
144                    dimnames(data) <- dimnames
145                }
146              if(is.null(sparse))              if(is.null(sparse))
147                  sparse <- sparseDefault(data)                  sparse <- sparseDefault(data)
dimnames(data) <- dimnames
148          }          }
149          doDN <- FALSE          doDN <- FALSE
150      }      } else if(!missing(nrow) || !missing(ncol)|| !missing(byrow))
151            warning("'nrow', 'ncol', etc, are disregarded for matrix 'data'")
152
153      ## 'data' is now a "matrix" or "Matrix"      ## 'data' is now a "matrix" or "Matrix"
154      if (doDN && !is.null(dimnames))      if (doDN && !is.null(dimnames))
155          dimnames(data) <- dimnames          dimnames(data) <- dimnames
# Line 158  Line 192
192                    }, sep="")                    }, sep="")
193          }          }
194
195      ## Now coerce and return      ## Can we coerce and be done?
196        if(!canCoerce(data,cl)) { ## try to coerce ``via'' virtual classes
197            if(sparse && !sM)
198                data <- as(data, "sparseMatrix")
199            else if(!sparse && !is(data, "denseMatrix"))
200                data <- as(data, "denseMatrix")
201            if(isTri && !is(data, "triangularMatrix"))
202                data <- as(data, "triangularMatrix")
203            else if(isSym && !is(data, "symmetricMatrix"))
204                data <- as(data, "symmetricMatrix")
205        }
206        ## now coerce in any case .. maybe producing sensible error message:
207      as(data, cl)      as(data, cl)
208  }  }
209
# Line 169  Line 214
214
215  setMethod("%*%", signature(x = "Matrix", y = "numeric"),  setMethod("%*%", signature(x = "Matrix", y = "numeric"),
216            function(x, y) callGeneric(x, as.matrix(y)))            function(x, y) callGeneric(x, as.matrix(y)))

217  setMethod("%*%", signature(x = "numeric", y = "Matrix"),  setMethod("%*%", signature(x = "numeric", y = "Matrix"),
218            function(x, y) callGeneric(matrix(x, nrow = 1, byrow=TRUE), y))            function(x, y) callGeneric(matrix(x, nrow = 1, byrow=TRUE), y))
219
220    setMethod("%*%", signature(x = "Matrix", y = "matrix"),
221              function(x, y) callGeneric(x, Matrix(y)))
222    setMethod("%*%", signature(x = "matrix", y = "Matrix"),
223              function(x, y) callGeneric(Matrix(x), y))
224
225
226  setMethod("crossprod", signature(x = "Matrix", y = "numeric"),  setMethod("crossprod", signature(x = "Matrix", y = "numeric"),
227            function(x, y = NULL) callGeneric(x, as.matrix(y)))            function(x, y = NULL) callGeneric(x, as.matrix(y)))
228  setMethod("crossprod", signature(x = "numeric", y = "Matrix"),  setMethod("crossprod", signature(x = "numeric", y = "Matrix"),
229            function(x, y = NULL)  callGeneric(as.matrix(x), y))            function(x, y = NULL)  callGeneric(as.matrix(x), y))
230
231    setMethod("crossprod", signature(x = "Matrix", y = "matrix"),
232              function(x, y = NULL) callGeneric(x, Matrix(y)))
233    setMethod("crossprod", signature(x = "matrix", y = "Matrix"),
234              function(x, y = NULL) callGeneric(Matrix(x), y))
235
236  ## The as.matrix() promotion seems illogical to MM,  ## The as.matrix() promotion seems illogical to MM,
237  ## but is according to help(tcrossprod, package = "base") :  ## but is according to help(tcrossprod, package = "base") :
238  setMethod("tcrossprod", signature(x = "Matrix", y = "numeric"),  setMethod("tcrossprod", signature(x = "Matrix", y = "numeric"),
239            function(x, y = NULL) callGeneric(x, as.matrix(y)))            function(x, y = NULL) callGeneric(x, as.matrix(y)))
240  setMethod("tcrossprod", signature(x = "numeric", y = "Matrix"),  setMethod("tcrossprod", signature(x = "numeric", y = "Matrix"),
241            function(x, y = NULL)  callGeneric(as.matrix(x), y))            function(x, y = NULL)  callGeneric(as.matrix(x), y))
242    setMethod("tcrossprod", signature(x = "Matrix", y = "matrix"),
243              function(x, y = NULL) callGeneric(x, Matrix(y)))
244    setMethod("tcrossprod", signature(x = "matrix", y = "Matrix"),
245              function(x, y = NULL) callGeneric(Matrix(x), y))
246
247  ## maybe not optimal  ## maybe not 100% optimal, but elegant:
248  setMethod("solve", signature(a = "Matrix", b = "missing"),  setMethod("solve", signature(a = "Matrix", b = "missing"),
249            function(a, b, ...) solve(a, Diagonal(nrow(a))))            function(a, b, ...) solve(a, Diagonal(nrow(a))))
250
251  setMethod("solve", signature(a = "Matrix", b = "numeric"),  setMethod("solve", signature(a = "Matrix", b = "numeric"),
252            function(a, b, ...) callGeneric(a, as.matrix(b)))            function(a, b, ...) callGeneric(a, Matrix(b)))
## when no sub-class method is found, bail out
253  setMethod("solve", signature(a = "Matrix", b = "matrix"),  setMethod("solve", signature(a = "Matrix", b = "matrix"),
254            function(a, b, ...) .bail.out.2("solve", class(a), "matrix"))            function(a, b, ...) callGeneric(a, Matrix(b)))
255    setMethod("solve", signature(a = "matrix", b = "Matrix"),
256              function(a, b, ...) callGeneric(Matrix(a), b))
257
258    ## when no sub-class method is found, bail out
259    setMethod("solve", signature(a = "Matrix", b = "Matrix"),
260              function(a, b, ...) .bail.out.2("solve", class(a), class(b)))
261
262  ## bail-out methods in order to get better error messages  ## bail-out methods in order to get better error messages
263  setMethod("%*%", signature(x = "Matrix", y = "Matrix"),  setMethod("%*%", signature(x = "Matrix", y = "Matrix"),
# Line 220  Line 284
284  setMethod("kronecker", signature(X = "Matrix", Y = "ANY",  setMethod("kronecker", signature(X = "Matrix", Y = "ANY",
285                                   FUN = "ANY", make.dimnames = "ANY"),                                   FUN = "ANY", make.dimnames = "ANY"),
286            function(X, Y, FUN, make.dimnames, ...) {            function(X, Y, FUN, make.dimnames, ...) {
287                  if(is(X, "sparseMatrix"))
288                      warning("using slow kronecker() method")
289                X <- as(X, "matrix") ; Matrix(callGeneric()) })                X <- as(X, "matrix") ; Matrix(callGeneric()) })
290
291  setMethod("kronecker", signature(X = "ANY", Y = "Matrix",  setMethod("kronecker", signature(X = "ANY", Y = "Matrix",
292                                   FUN = "ANY", make.dimnames = "ANY"),                                   FUN = "ANY", make.dimnames = "ANY"),
293            function(X, Y, FUN, make.dimnames, ...) {            function(X, Y, FUN, make.dimnames, ...) {
294                  if(is(Y, "sparseMatrix"))
295                      warning("using slow kronecker() method")
296                Y <- as(Y, "matrix") ; Matrix(callGeneric()) })                Y <- as(Y, "matrix") ; Matrix(callGeneric()) })
297
298
# Line 238  Line 307
307  setMethod("t", signature(x = "Matrix"),  setMethod("t", signature(x = "Matrix"),
308            function(x) .bail.out.1(.Generic, class(x)))            function(x) .bail.out.1(.Generic, class(x)))
309
310  ## Group Methods  setMethod("norm", signature(x = "Matrix", type = "character"),
311  setMethod("+", signature(e1 = "Matrix", e2 = "missing"), function(e1) e1)            function(x, type, ...) .bail.out.1(.Generic, class(x)))
312  ## "fallback":  setMethod("rcond", signature(x = "Matrix", type = "character"),
313  setMethod("-", signature(e1 = "Matrix", e2 = "missing"),            function(x, type, ...) .bail.out.1(.Generic, class(x)))
314            function(e1) {
315                warning("inefficient method used for \"- e1\"")
316                0-e1  ## for all :
317    setMethod("norm", signature(x = "ANY", type = "missing"),
318              function(x, type, ...) norm(x, type = "O", ...))
319    setMethod("rcond", signature(x = "ANY", type = "missing"),
320              function(x, type, ...) rcond(x, type = "O", ...))
321
322
323
324
325
326    ## MM: More or less "Cut & paste" from
327    ## --- diff.default() from  R/src/library/base/R/diff.R :
328    setMethod("diff", signature(x = "Matrix"),
329              function(x, lag = 1, differences = 1, ...) {
330                  if (length(lag) > 1 || length(differences) > 1 ||
331                      lag < 1 || differences < 1)
332                      stop("'lag' and 'differences' must be integers >= 1")
333                  xlen <- nrow(x)
334                  if (lag * differences >= xlen)
335                      return(x[,FALSE][0])  # empty of proper mode
336
337                  i1 <- -1:-lag
338                  for (i in 1:differences)
339                      x <- x[i1, , drop = FALSE] -
340                          x[-nrow(x):-(nrow(x)-lag+1), , drop = FALSE]
341                  x
342            })            })
343
344  ## old-style matrices are made into new ones  setMethod("image", "Matrix",
345  setMethod("Ops", signature(e1 = "Matrix", e2 = "matrix"),            function(x, ...) { # coercing to sparse is not inefficient,
346            function(e1, e2) callGeneric(e1, Matrix(e2)))                ##               since we need 'i' and 'j' for levelplot()
347  ##          callGeneric(e1, Matrix(e2, sparse=is(e1,"sparseMatrix"))))                x <- as(as(x, "sparseMatrix"), "dMatrix")
348  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))
349            })            })
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)))
350
351
352    ## Group Methods
353
354    ##-> see ./Ops.R
355    ##         ~~~~~
356    ## For all  non-dMatrix objects, and note that  "all" and "any" have their own
357    setMethod("Summary", signature(x = "Matrix", na.rm = "ANY"),
358              function(x, ..., na.rm)
359              callGeneric(as(x,"dMatrix"), ..., na.rm = na.rm))
360
361
362  ### --------------------------------------------------------------------------  ### --------------------------------------------------------------------------
363  ###  ###
# Line 278  Line 370
370  ## "x[]":  ## "x[]":
371  setMethod("[", signature(x = "Matrix",  setMethod("[", signature(x = "Matrix",
372                           i = "missing", j = "missing", drop = "ANY"),                           i = "missing", j = "missing", drop = "ANY"),
373            function (x, i, j, drop) x)            function (x, i, j, ..., drop) x)
374
375  ## missing 'drop' --> 'drop = TRUE'  ## missing 'drop' --> 'drop = TRUE'
376  ##                     -----------  ##                     -----------
377  ## select rows  ## select rows
378  setMethod("[", signature(x = "Matrix", i = "index", j = "missing",  setMethod("[", signature(x = "Matrix", i = "index", j = "missing",
379                           drop = "missing"),                           drop = "missing"),
380            function(x,i,j, drop) callGeneric(x, i=i, drop= TRUE))            function(x,i,j, ..., drop) {
381                  if(nargs() == 1) { ## e.g. M[0] , M[TRUE],  M[1:2]
382                      if(any(i)) as.vector(x)[i] else as.vector(x[1,1])[FALSE]
383                  } else callGeneric(x, i=i, drop= TRUE)})
384
385  ## select columns  ## select columns
386  setMethod("[", signature(x = "Matrix", i = "missing", j = "index",  setMethod("[", signature(x = "Matrix", i = "missing", j = "index",
387                           drop = "missing"),                           drop = "missing"),
388            function(x,i,j, drop) callGeneric(x, j=j, drop= TRUE))            function(x,i,j, ..., drop) callGeneric(x, j=j, drop= TRUE))
389  setMethod("[", signature(x = "Matrix", i = "index", j = "index",  setMethod("[", signature(x = "Matrix", i = "index", j = "index",
390                           drop = "missing"),                           drop = "missing"),
391            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))
392
393  ## bail out if any of (i,j,drop) is "non-sense"  ## bail out if any of (i,j,drop) is "non-sense"
394  setMethod("[", signature(x = "Matrix", i = "ANY", j = "ANY", drop = "ANY"),  setMethod("[", signature(x = "Matrix", i = "ANY", j = "ANY", drop = "ANY"),
395            function(x,i,j, drop)            function(x,i,j, ..., drop)
396            stop("invalid or not-yet-implemented 'Matrix' subsetting"))            stop("invalid or not-yet-implemented 'Matrix' subsetting"))
397
398  ## 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,],
399  ## The following is *both* for    M [ <logical>   ]  ## The following is *both* for    M [ <logical>   ]
400  ##                 and also for   M [ <logical> , ]  ##                 and also for   M [ <logical> , ]
401  .M.sub.i.logical <- function (x, i, j, drop)  .M.sub.i.logical <- function (x, i, j, ..., drop)
402  {  {
403      nA <- nargs()      nA <- nargs()
404      if(nA == 2) { ##  M [ M >= 7 ]      if(nA == 2) { ##  M [ M >= 7 ]
# Line 313  Line 409
409          stop("not-yet-implemented 'Matrix' subsetting") ## FIXME          stop("not-yet-implemented 'Matrix' subsetting") ## FIXME
410
411      } else stop("nargs() = ", nA,      } else stop("nargs() = ", nA,
412                  " should never happen; please report.")                  ".  Extraneous illegal arguments inside '[ .. ]' (i.logical)?")
413  }  }
414  setMethod("[", signature(x = "Matrix", i = "lMatrix", j = "missing",  setMethod("[", signature(x = "Matrix", i = "lMatrix", j = "missing",
415                           drop = "ANY"),                           drop = "ANY"),
# Line 324  Line 420
420
421
422  ## A[ ij ]  where ij is (i,j) 2-column matrix :  ## A[ ij ]  where ij is (i,j) 2-column matrix :
423  .M.sub.i.2col <- function (x, i, j, drop)  .M.sub.i.2col <- function (x, i, j, ..., drop)
424  {  {
425      nA <- nargs()      nA <- nargs()
426      if(nA == 2) { ##  M [ cbind(ii,jj) ]      if(nA == 2) { ##  M [ cbind(ii,jj) ]
# Line 343  Line 439
439          ## potentially inefficient -- FIXME --          ## potentially inefficient -- FIXME --
440          unlist(lapply(seq_len(m), function(j) x[i1[j], i2[j]]))          unlist(lapply(seq_len(m), function(j) x[i1[j], i2[j]]))
441
442      } else stop("nargs() = ", nA, " should never happen; please report.")      } else stop("nargs() = ", nA,
443                    ".  Extraneous illegal arguments inside '[ .. ]' (i.2col)?")
444  }  }
445  setMethod("[", signature(x = "Matrix", i = "matrix", j = "missing"),# drop="ANY"  setMethod("[", signature(x = "Matrix", i = "matrix", j = "missing"),# drop="ANY"
446            .M.sub.i.2col)            .M.sub.i.2col)
# Line 356  Line 453
453                                  value = "ANY"),## double/logical/...                                  value = "ANY"),## double/logical/...
454            function (x, value) {            function (x, value) {
455                ## Fails for 'nMatrix' ... FIXME : make sure have method there                ## Fails for 'nMatrix' ... FIXME : make sure have method there
456                x@x <- value                x@x <- rep(value, length = length(x@x))
457                validObject(x)# check if type and lengths above match                validObject(x)# check if type and lengths above match
458                x                x
459            })            })
460
461  ## A[ ij ] <- value,  where ij is (i,j) 2-column matrix :  ## A[ ij ] <- value,  where ij is (i,j) 2-column matrix :
462  .M.repl.i.2col <- function (x, i, j, value)  ## ----------------
463    ## The cheap general method --- FIXME: provide special ones; done for Tsparse..
464    ## NOTE:  need '...' below such that setMethod() does
465    ##        not use .local() such that nargs() will work correctly:
466    .M.repl.i.2col <- function (x, i, j, ..., value)
467  {  {
468      nA <- nargs()      nA <- nargs()
469      if(nA == 3) { ##  M [ cbind(ii,jj) ] <- value      if(nA == 3) { ##  M [ cbind(ii,jj) ] <- value
470          if(!is.integer(nc <- ncol(i)))          if(!is.integer(nc <- ncol(i)))
471              stop("'i' has no integer column number",              stop("'i' has no integer column number",
472                   " should never happen; please report")                   " should never happen; please report")
473            else if(!is.numeric(i) || nc != 2)
474                stop("such indexing must be by logical or 2-column numeric matrix")
475          if(is.logical(i)) {          if(is.logical(i)) {
476                message(".M.repl.i.2col(): drop 'matrix' case ...")
477              i <- c(i) # drop "matrix"              i <- c(i) # drop "matrix"
478              return( callNextMethod() )              return( callNextMethod() )
479          } else if(!is.numeric(i) || nc != 2)          }
480              stop("such indexing must be by logical or 2-column numeric matrix")          if(!is.integer(i)) storage.mode(i) <- "integer"
481            if(any(i < 0))
482                stop("negative values are not allowed in a matrix subscript")
483            if(any(is.na(i)))
484                stop("NAs are not allowed in subscripted assignments")
485            if(any(i0 <- (i == 0))) # remove them
486                i <- i[ - which(i0, arr.ind = TRUE)[,"row"], ]
487            ## now have integer i >= 1
488          m <- nrow(i)          m <- nrow(i)
489          mod.x <- .type.kind[.M.kind(x)]          ## mod.x <- .type.kind[.M.kind(x)]
490          if(length(value) > 0 && m %% length(value) != 0)          if(length(value) > 0 && m %% length(value) != 0)
491              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")
492          ## recycle:          ## recycle:
# Line 385  Line 496
496          ## inefficient -- FIXME -- (also loses "symmetry" unnecessarily)          ## inefficient -- FIXME -- (also loses "symmetry" unnecessarily)
497          for(k in seq_len(m))          for(k in seq_len(m))
498              x[i1[k], i2[k]] <- value[k]              x[i1[k], i2[k]] <- value[k]
x
499
500      } else stop("nargs() = ", nA, " should never happen; please report.")          x
501        } else stop("nargs() = ", nA,
502                    ".  Extraneous illegal arguments inside '[ .. ]' ?")
503  }  }
504
505  setReplaceMethod("[", signature(x = "Matrix", i = "matrix", j = "missing",  setReplaceMethod("[", signature(x = "Matrix", i = "matrix", j = "missing",
506                                  value = "replValue"),                                  value = "replValue"),
507            .M.repl.i.2col)            .M.repl.i.2col)
508
509
510    setReplaceMethod("[", signature(x = "Matrix", i = "missing", j = "ANY",
511                                    value = "Matrix"),
512                     function (x, i, j, ..., value)
513                     callGeneric(x=x, j=j, value = as.vector(value)))
514
515    setReplaceMethod("[", signature(x = "Matrix", i = "ANY", j = "missing",
516                                    value = "Matrix"),
517                     function (x, i, j, ..., value)
518                     callGeneric(x=x, i=i, value = as.vector(value)))
519
520  setReplaceMethod("[", signature(x = "Matrix", i = "ANY", j = "ANY",  setReplaceMethod("[", signature(x = "Matrix", i = "ANY", j = "ANY",
521                                  value = "Matrix"),                                  value = "Matrix"),
522                   function (x, i, j, value)                   function (x, i, j, ..., value)
523                   callGeneric(x=x, i=i, j=j, value = as.vector(value)))                   callGeneric(x=x, i=i, j=j, value = as.vector(value)))
524
525    setReplaceMethod("[", signature(x = "Matrix", i = "missing", j = "ANY",
526                                    value = "matrix"),
527                     function (x, i, j, ..., value)
528                     callGeneric(x=x, j=j, value = c(value)))
529
530    setReplaceMethod("[", signature(x = "Matrix", i = "ANY", j = "missing",
531                                    value = "matrix"),
532                     function (x, i, j, ..., value)
533                     callGeneric(x=x, i=i, value = c(value)))
534
535  setReplaceMethod("[", signature(x = "Matrix", i = "ANY", j = "ANY",  setReplaceMethod("[", signature(x = "Matrix", i = "ANY", j = "ANY",
536                                  value = "matrix"),                                  value = "matrix"),
537                   function (x, i, j, value)                   function (x, i, j, value)
# Line 412  Line 546
546                                 class(value),class(x)))                                 class(value),class(x)))
547                else stop("not-yet-implemented 'Matrix[<-' method")                else stop("not-yet-implemented 'Matrix[<-' method")
548            })            })

## 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.2081