SCM

SCM Repository

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

Diff of /pkg/R/Matrix.R

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

revision 1290, Thu Jun 8 09:30:21 2006 UTC revision 1829, Thu Apr 26 06:35:20 2007 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:
31    setMethod("head", signature(x = "Matrix"), utils::head.matrix)
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  ## Note that isSymmetric is *not* exported  
48  ## but that "base" has an isSymmetric() S3-generic since R 2.3.0  ## "base" has an isSymmetric() S3-generic since R 2.3.0
49  setMethod("isSymmetric", signature(object = "symmetricMatrix"),  setMethod("isSymmetric", signature(object = "symmetricMatrix"),
50            function(object,tol) TRUE)            function(object,tol) TRUE)
51  setMethod("isSymmetric", signature(object = "triangularMatrix"),  setMethod("isSymmetric", signature(object = "triangularMatrix"),
52            ## TRUE iff diagonal:            ## TRUE iff diagonal:
53            function(object,tol) isDiagonal(object))            function(object,tol) isDiagonal(object))
54    
 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)  
           })  
   
   
55  setMethod("isTriangular", signature(object = "triangularMatrix"),  setMethod("isTriangular", signature(object = "triangularMatrix"),
56            function(object, ...) TRUE)            function(object, ...) TRUE)
57    
# 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) { x <- as(x, "lMatrix"); callGeneric()})
92    setMethod("any", signature(x = "Matrix"),
93              function(x, ..., na.rm) { x <- as(x, "lMatrix"); callGeneric()})
94    
95    setMethod("!", "Matrix", function(e1) !as(e1, "lMatrix"))
96    
97    
98    
99  Matrix <-  Matrix <-
100      function (data = NA, nrow = 1, ncol = 1, byrow = FALSE, dimnames = NULL,      function (data = NA, nrow = 1, ncol = 1, byrow = FALSE, dimnames = NULL,
101                sparse = NULL)                sparse = NULL, forceCheck = FALSE)
102  {  {
103      sparseDefault <- function(m)      sparseDefault <- function(m) prod(dim(m)) > 2*sum(isN0(as(m, "matrix")))
         prod(dim(m)) > 2*sum(as(m, "matrix") != 0)  
104    
105      i.M <- is(data, "Matrix")      i.M <- is(data, "Matrix")
106      if(is.null(sparse) && (i.M || is(data, "matrix")))  
107        if(is.null(sparse1 <- sparse) && (i.M || is(data, "matrix")))
108          sparse <- sparseDefault(data)          sparse <- sparseDefault(data)
109    
110        doDN <- TRUE
111      if (i.M) {      if (i.M) {
112            if(!missing(nrow) || !missing(ncol)|| !missing(byrow))
113                warning("'nrow', 'ncol', etc, are disregarded when 'data' is \"Matrix\" already")
114          sM <- is(data,"sparseMatrix")          sM <- is(data,"sparseMatrix")
115          if((sparse && sM) || (!sparse && !sM))          if(!forceCheck && ((sparse && sM) || (!sparse && !sM)))
116              return(data)              return(data)
117          ## else : convert  dense <-> sparse -> at end          ## else : convert  dense <-> sparse -> at end
118      }      }
# Line 97  Line 121 
121              nrow <- ceiling(length(data)/ncol)              nrow <- ceiling(length(data)/ncol)
122          else if (missing(ncol))          else if (missing(ncol))
123              ncol <- ceiling(length(data)/nrow)              ncol <- ceiling(length(data)/nrow)
124            if(length(data) == 1 && is0(data) && !identical(sparse, FALSE)) {
125                ## Matrix(0, ...) : always sparse unless "sparse = FALSE":
126                if(is.null(sparse)) sparse1 <- sparse <- TRUE
127                i.M <- sM <- TRUE
128                ## will be sparse: do NOT construct full matrix!
129                data <- new(if(is.numeric(data)) "dgTMatrix" else
130                            if(is.logical(data)) "lgTMatrix" else
131                            stop("invalid 'data'"),
132                            Dim = as.integer(c(nrow,ncol)),
133                            Dimnames = if(is.null(dimnames)) list(NULL,NULL)
134                            else dimnames)
135            } else { ## normal case
136          data <- .Internal(matrix(data, nrow, ncol, byrow))          data <- .Internal(matrix(data, nrow, ncol, byrow))
137          if(is.null(sparse))          if(is.null(sparse))
138              sparse <- sparseDefault(data)              sparse <- sparseDefault(data)
139          dimnames(data) <- dimnames          dimnames(data) <- dimnames
140      } else if (!is.null(dimnames))          }
141          dimnames(data) <- dimnames          doDN <- FALSE
142        } else if(!missing(nrow) || !missing(ncol)|| !missing(byrow))
143            warning("'nrow', 'ncol', etc, are disregarded for matrix 'data'")
144    
145      ## 'data' is now a "matrix" or "Matrix"      ## 'data' is now a "matrix" or "Matrix"
146        if (doDN && !is.null(dimnames))
147            dimnames(data) <- dimnames
148    
149      ## check for symmetric / triangular / diagonal :      ## check for symmetric / triangular / diagonal :
150      isSym <- isSymmetric(data)      isSym <- isSymmetric(data)
# Line 114  Line 154 
154      if(isDiag)      if(isDiag)
155          isDiag <- isDiagonal(data)          isDiag <- isDiagonal(data)
156    
 ### TODO: Compare with as.Matrix() and its tests in ./dgeMatrix.R  
   
157      ## Find proper matrix class 'cl'      ## Find proper matrix class 'cl'
158      cl <-      cl <-
159          if(isDiag)          if(isDiag && !isTRUE(sparse1))
160              "diagonalMatrix" # -> will automatically check for type              "diagonalMatrix" # -> will automatically check for type
161          else {          else {
162              ## consider it's type              ## consider it's type
# Line 146  Line 184 
184                    }, sep="")                    }, sep="")
185          }          }
186    
187      ## Now coerce and return      ## Can we coerce and be done?
188        if(!canCoerce(data,cl)) { ## try to coerce ``via'' virtual classes
189            if(sparse && !sM)
190                data <- as(data, "sparseMatrix")
191            else if(!sparse && !is(data, "denseMatrix"))
192                data <- as(data, "denseMatrix")
193            if(isTri && !is(data, "triangularMatrix"))
194                data <- as(data, "triangularMatrix")
195            else if(isSym && !is(data, "symmetricMatrix"))
196                data <- as(data, "symmetricMatrix")
197        }
198        ## now coerce in any case .. maybe producing sensible error message:
199      as(data, cl)      as(data, cl)
200  }  }
201    
# Line 159  Line 208 
208            function(x, y) callGeneric(x, as.matrix(y)))            function(x, y) callGeneric(x, as.matrix(y)))
209    
210  setMethod("%*%", signature(x = "numeric", y = "Matrix"),  setMethod("%*%", signature(x = "numeric", y = "Matrix"),
211            function(x, y) callGeneric(rbind(x), y))            function(x, y) callGeneric(matrix(x, nrow = 1, byrow=TRUE), y))
212    
213  setMethod("crossprod", signature(x = "Matrix", y = "numeric"),  setMethod("crossprod", signature(x = "Matrix", y = "numeric"),
214            function(x, y = NULL) callGeneric(x, as.matrix(y)))            function(x, y = NULL) callGeneric(x, as.matrix(y)))
   
215  setMethod("crossprod", signature(x = "numeric", y = "Matrix"),  setMethod("crossprod", signature(x = "numeric", y = "Matrix"),
216            function(x, y = NULL)  callGeneric(rbind(x), y))            function(x, y = NULL)  callGeneric(as.matrix(x), y))
217    
218    ## The as.matrix() promotion seems illogical to MM,
219    ## but is according to help(tcrossprod, package = "base") :
220    setMethod("tcrossprod", signature(x = "Matrix", y = "numeric"),
221              function(x, y = NULL) callGeneric(x, as.matrix(y)))
222    setMethod("tcrossprod", signature(x = "numeric", y = "Matrix"),
223              function(x, y = NULL)  callGeneric(as.matrix(x), y))
224    
225    ## maybe not optimal
226    setMethod("solve", signature(a = "Matrix", b = "missing"),
227              function(a, b, ...) solve(a, Diagonal(nrow(a))))
228    
229  setMethod("solve", signature(a = "Matrix", b = "numeric"),  setMethod("solve", signature(a = "Matrix", b = "numeric"),
230            function(a, b, ...) callGeneric(a, as.matrix(b)))            function(a, b, ...) callGeneric(a, as.matrix(b)))
231    ## when no sub-class method is found, bail out
232    setMethod("solve", signature(a = "Matrix", b = "matrix"),
233              function(a, b, ...) .bail.out.2("solve", class(a), "matrix"))
234    setMethod("solve", signature(a = "Matrix", b = "Matrix"),
235              function(a, b, ...) .bail.out.2("solve", class(a), class(b)))
236    
237  ## bail-out methods in order to get better error messages  ## bail-out methods in order to get better error messages
238  setMethod("%*%", signature(x = "Matrix", y = "Matrix"),  setMethod("%*%", signature(x = "Matrix", y = "Matrix"),
# Line 180  Line 244 
244            function (x, y = NULL) .bail.out.2(.Generic, class(x), class(y)))            function (x, y = NULL) .bail.out.2(.Generic, class(x), class(y)))
245  setMethod("crossprod", signature(x = "ANY", y = "Matrix"),  setMethod("crossprod", signature(x = "ANY", y = "Matrix"),
246            function (x, y = NULL) .bail.out.2(.Generic, class(x), class(y)))            function (x, y = NULL) .bail.out.2(.Generic, class(x), class(y)))
247    setMethod("tcrossprod", signature(x = "Matrix", y = "ANY"),
248              function (x, y = NULL) .bail.out.2(.Generic, class(x), class(y)))
249    setMethod("tcrossprod", signature(x = "ANY", y = "Matrix"),
250              function (x, y = NULL) .bail.out.2(.Generic, class(x), class(y)))
251    
252    ## cheap fallbacks
253    setMethod("crossprod", signature(x = "Matrix", y = "Matrix"),
254              function(x, y = NULL) t(x) %*% y)
255    setMethod("tcrossprod", signature(x = "Matrix", y = "Matrix"),
256              function(x, y = NULL) x %*% t(y))
257    
258  ## There are special sparse methods; this is a "fall back":  ## There are special sparse methods; this is a "fall back":
259  setMethod("kronecker", signature(X = "Matrix", Y = "ANY",  setMethod("kronecker", signature(X = "Matrix", Y = "ANY",
260                                   FUN = "ANY", make.dimnames = "ANY"),                                   FUN = "ANY", make.dimnames = "ANY"),
261            function(X, Y, FUN, make.dimnames, ...) {            function(X, Y, FUN, make.dimnames, ...) {
262                  if(is(X, "sparseMatrix"))
263                      warning("using slow kronecker() method")
264                X <- as(X, "matrix") ; Matrix(callGeneric()) })                X <- as(X, "matrix") ; Matrix(callGeneric()) })
265    
266  setMethod("kronecker", signature(X = "ANY", Y = "Matrix",  setMethod("kronecker", signature(X = "ANY", Y = "Matrix",
267                                   FUN = "ANY", make.dimnames = "ANY"),                                   FUN = "ANY", make.dimnames = "ANY"),
268            function(X, Y, FUN, make.dimnames, ...) {            function(X, Y, FUN, make.dimnames, ...) {
269                  if(is(Y, "sparseMatrix"))
270                      warning("using slow kronecker() method")
271                Y <- as(Y, "matrix") ; Matrix(callGeneric()) })                Y <- as(Y, "matrix") ; Matrix(callGeneric()) })
272    
273    
274    ## FIXME: All of these should never be called
275    setMethod("chol", signature(x = "Matrix"),
276              function(x, pivot = FALSE) .bail.out.1(.Generic, class(x)))
277    setMethod("determinant", signature(x = "Matrix"),
278              function(x, logarithm = TRUE) .bail.out.1(.Generic, class(x)))
279    
280    setMethod("diag", signature(x = "Matrix"),
281              function(x, nrow, ncol) .bail.out.1(.Generic, class(x)))
282  setMethod("t", signature(x = "Matrix"),  setMethod("t", signature(x = "Matrix"),
283            function(x) .bail.out.1(.Generic, class(x)))            function(x) .bail.out.1(.Generic, class(x)))
284    
285  ## Group Methods  setMethod("dim<-", signature(x = "Matrix", value = "ANY"),
286  setMethod("+", signature(e1 = "Matrix", e2 = "missing"), function(e1) e1)            function(x, value) {
287  ## "fallback":                if(!is.numeric(value) || length(value) != 2)
288  setMethod("-", signature(e1 = "Matrix", e2 = "missing"),                    stop("dim(.) value must be numeric of length 2")
289            function(e1) {                if(prod(dim(x)) != prod(value <- as.integer(value)))
290                warning("inefficient method used for \"- e1\"")                    stop("dimensions don't match the number of cells")
291                0-e1                clx <- class(x)
292                  if(substring(clx,2) == "geMatrix") {
293                      x@Dim <- value
294                      if(length(x@factors) > 0)
295                          x@factors <- list()
296                      x
297                  } else if(extends(clx, "denseMatrix")) {
298                      x <- as_geSimpl2(x, clx)
299                      dim(x) <- value
300                  } else { ## FIXME: this is very inefficient for large sparse x
301                      Matrix(as.vector(x), value[1], value[2])
302                  }
303            })            })
304    
305  ## bail-outs:  ## MM: More or less "Cut & paste" from
306  setMethod("Compare", signature(e1 = "Matrix", e2 = "Matrix"),  ## --- diff.default() from  R/src/library/base/R/diff.R :
307            function(e1, e2) {  setMethod("diff", signature(x = "Matrix"),
308                d <- dimCheck(e1,e2)            function(x, lag = 1, differences = 1, ...) {
309                .bail.out.2(.Generic, class(e1), class(e2))                if (length(lag) > 1 || length(differences) > 1 ||
310                      lag < 1 || differences < 1)
311                      stop("'lag' and 'differences' must be integers >= 1")
312                  xlen <- nrow(x)
313                  if (lag * differences >= xlen)
314                      return(x[,FALSE][0])  # empty of proper mode
315    
316                  i1 <- -1:-lag
317                  for (i in 1:differences)
318                      x <- x[i1, , drop = FALSE] -
319                          x[-nrow(x):-(nrow(x)-lag+1), , drop = FALSE]
320                  x
321              })
322    
323    setMethod("image", "Matrix",
324              function(x, ...) { # coercing to sparse is not inefficient,
325                  ##               since we need 'i' and 'j' for levelplot()
326                  x <- as(as(x, "sparseMatrix"), "dMatrix")
327                  callGeneric()
328            })            })
 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)))  
329    
330    
331    ## Group Methods
332    
333    ##-> see ./Ops.R
334    
335  ### --------------------------------------------------------------------------  ### --------------------------------------------------------------------------
336  ###  ###
# Line 235  Line 350 
350  ## select rows  ## select rows
351  setMethod("[", signature(x = "Matrix", i = "index", j = "missing",  setMethod("[", signature(x = "Matrix", i = "index", j = "missing",
352                           drop = "missing"),                           drop = "missing"),
353            function(x,i,j, drop) callGeneric(x, i=i, drop= TRUE))            function(x,i,j, drop) {
354                  if(nargs() == 1) { ## e.g. M[0] , M[TRUE],  M[1:2]
355                      if(any(i)) as.vector(x)[i] else as.vector(x[1,1])[FALSE]
356                  } else callGeneric(x, i=i, drop= TRUE)})
357    
358  ## select columns  ## select columns
359  setMethod("[", signature(x = "Matrix", i = "missing", j = "index",  setMethod("[", signature(x = "Matrix", i = "missing", j = "index",
360                           drop = "missing"),                           drop = "missing"),
# Line 249  Line 368 
368            function(x,i,j, drop)            function(x,i,j, drop)
369            stop("invalid or not-yet-implemented 'Matrix' subsetting"))            stop("invalid or not-yet-implemented 'Matrix' subsetting"))
370    
371  ##  "logical *vector* indexing, such as  M [ M >= 10 ] :  ## logical indexing, such as M[ M >= 7 ] *BUT* also M[ M[,1] >= 3,],
372  setMethod("[", signature(x = "Matrix", i = "lMatrix", j = "missing",  ## The following is *both* for    M [ <logical>   ]
373                           drop = "ANY"),  ##                 and also for   M [ <logical> , ]
374            function (x, i, j, drop) {  .M.sub.i.logical <- function (x, i, j, drop)
375    {
376        nA <- nargs()
377        if(nA == 2) { ##  M [ M >= 7 ]
378            ## FIXME: when both 'x' and 'i' are sparse, this can be very inefficient
379                as(x, geClass(x))@x[as.vector(i)]                as(x, geClass(x))@x[as.vector(i)]
380                                          # -> error when lengths don't match          ## -> error when lengths don't match
381            })      } else if(nA == 3) { ##  M [ M[,1, drop=FALSE] >= 7, ]
382            stop("not-yet-implemented 'Matrix' subsetting") ## FIXME
383    
384        } else stop("nargs() = ", nA,
385                    ".  Extraneous illegal arguments inside '[ .. ]' ?")
386    }
387    setMethod("[", signature(x = "Matrix", i = "lMatrix", j = "missing",
388                             drop = "ANY"),
389              .M.sub.i.logical)
390  setMethod("[", signature(x = "Matrix", i = "logical", j = "missing",  setMethod("[", signature(x = "Matrix", i = "logical", j = "missing",
391                           drop = "ANY"),                           drop = "ANY"),
392            function (x, i, j, drop) as(x, geClass(x))@x[i])            .M.sub.i.logical)
393    
394    
395  ## "FIXME:"  ## A[ ij ]  where ij is (i,j) 2-column matrix :
396  ## How can we get at   A[ ij ]  where ij is (i,j) 2-column matrix?  .M.sub.i.2col <- function (x, i, j, drop)
397  ##  and                A[ LL ]  where LL is a logical *vector*  {
398  ## -> [.data.frame uses nargs() - can we do this in the *generic* ?      nA <- nargs()
399        if(nA == 2) { ##  M [ cbind(ii,jj) ]
400            if(!is.integer(nc <- ncol(i)))
401                stop("'i' has no integer column number",
402                     " should never happen; please report")
403            if(is.logical(i))
404                return(.M.sub.i.logical(x,i,j,drop))
405            else if(!is.numeric(i) || nc != 2)
406                stop("such indexing must be by logical or 2-column numeric matrix")
407            m <- nrow(i)
408            if(m == 0) return(vector(mode = .type.kind[.M.kind(x)]))
409            ## else
410            i1 <- i[,1]
411            i2 <- i[,2]
412            ## potentially inefficient -- FIXME --
413            unlist(lapply(seq_len(m), function(j) x[i1[j], i2[j]]))
414    
415        } else stop("nargs() = ", nA,
416                    ".  Extraneous illegal arguments inside '[ .. ]' ?")
417    }
418    setMethod("[", signature(x = "Matrix", i = "matrix", j = "missing"),# drop="ANY"
419              .M.sub.i.2col)
420    
421    
422  ### "[<-" : -----------------  ### "[<-" : -----------------
# Line 274  Line 425 
425  setReplaceMethod("[", signature(x = "Matrix", i = "missing", j = "missing",  setReplaceMethod("[", signature(x = "Matrix", i = "missing", j = "missing",
426                                  value = "ANY"),## double/logical/...                                  value = "ANY"),## double/logical/...
427            function (x, value) {            function (x, value) {
428                x@x <- value                ## Fails for 'nMatrix' ... FIXME : make sure have method there
429                  x@x <- rep(value, length = length(x@x))
430                validObject(x)# check if type and lengths above match                validObject(x)# check if type and lengths above match
431                x                x
432            })            })
433    
434  ## Method for all 'Matrix' kinds (rather than incomprehensible error messages);  ## A[ ij ] <- value,  where ij is (i,j) 2-column matrix :
435    ## ----------------   The cheap general method --- FIXME: provide special ones
436    .M.repl.i.2col <- function (x, i, j, value)
437    {
438        nA <- nargs()
439        if(nA == 3) { ##  M [ cbind(ii,jj) ] <- value
440            if(!is.integer(nc <- ncol(i)))
441                stop("'i' has no integer column number",
442                     " should never happen; please report")
443            else if(!is.numeric(i) || nc != 2)
444                stop("such indexing must be by logical or 2-column numeric matrix")
445            if(is.logical(i)) {
446                message(".M.repl.i.2col(): drop 'matrix' case ...")
447                i <- c(i) # drop "matrix"
448                return( callNextMethod() )
449            }
450            if(!is.integer(i)) storage.mode(i) <- "integer"
451            if(any(i < 0))
452                stop("negative values are not allowed in a matrix subscript")
453            if(any(is.na(i)))
454                stop("NAs are not allowed in subscripted assignments")
455            if(any(i0 <- (i == 0))) # remove them
456                i <- i[ - which(i0, arr.ind = TRUE)[,"row"], ]
457            ## now have integer i >= 1
458            m <- nrow(i)
459            ## mod.x <- .type.kind[.M.kind(x)]
460            if(length(value) > 0 && m %% length(value) != 0)
461                warning("number of items to replace is not a multiple of replacement length")
462            ## recycle:
463            value <- rep(value, length = m)
464            i1 <- i[,1]
465            i2 <- i[,2]
466            ## inefficient -- FIXME -- (also loses "symmetry" unnecessarily)
467            for(k in seq_len(m))
468                x[i1[k], i2[k]] <- value[k]
469    
470            x
471        } else stop("nargs() = ", nA,
472                    ".  Extraneous illegal arguments inside '[ .. ]' ?")
473    }
474    
475    setReplaceMethod("[", signature(x = "Matrix", i = "matrix", j = "missing",
476                                    value = "replValue"),
477              .M.repl.i.2col)
478    
479    
480    setReplaceMethod("[", signature(x = "Matrix", i = "ANY", j = "ANY",
481                                    value = "Matrix"),
482                     function (x, i, j, value) {
483    ### *TEMPORARY* diagnostic output:
484    ##                  cat("<Matrix1>[i,j] <- <Matrix1>:\n<Matrix1> = x :")
485    ##                  str(x)
486    ##                  cat("<Matrix2> = value :")
487    ##                  str(value)
488    ##                  cat("i :"); if(!missing(i)) str(i) else cat("<missing>\n")
489    ##                  cat("j :"); if(!missing(j)) str(j) else cat("<missing>\n")
490    
491                         callGeneric(x=x, i=i, j=j, value = as.vector(value))
492                     })
493    setReplaceMethod("[", signature(x = "Matrix", i = "ANY", j = "ANY",
494                                    value = "Matrix"),
495                     function (x, i, j, value)
496                     callGeneric(x=x, i=i, j=j, value = as.vector(value)))
497    
498    setReplaceMethod("[", signature(x = "Matrix", i = "ANY", j = "ANY",
499                                    value = "matrix"),
500                     function (x, i, j, value)
501                     callGeneric(x=x, i=i, j=j, value = c(value)))
502    
503  ## (ANY,ANY,ANY) is used when no `real method' is implemented :  ## (ANY,ANY,ANY) is used when no `real method' is implemented :
504  setReplaceMethod("[", signature(x = "Matrix", i = "ANY", j = "ANY",  setReplaceMethod("[", signature(x = "Matrix", i = "ANY", j = "ANY",
505                                  value = "ANY"),                                  value = "ANY"),
506            function (x, i, j, value) {            function (x, i, j, value) {
507                if(!is.atomic(value))                if(!is.atomic(value))
508                    stop("RHS 'value' must match matrix class ", class(x))                    stop(sprintf("RHS 'value' (class %s) matches 'ANY', but must match matrix class %s",
509                                   class(value),class(x)))
510                else stop("not-yet-implemented 'Matrix[<-' method")                else stop("not-yet-implemented 'Matrix[<-' method")
511            })            })
   
   
 ## 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.1829

root@r-forge.r-project.org
ViewVC Help
Powered by ViewVC 1.0.0  
Thanks to:
Vienna University of Economics and Business Powered By FusionForge