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 1455, Mon Aug 28 15:35:44 2006 UTC revision 2062, Sat Sep 1 21:06:52 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:
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 19  Line 28 
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:  ## head and tail apply to all Matrix objects for which subscripting is allowed:
31  ## if(paste(R.version$major, R.version$minor, sep=".") < "2.4") {  setMethod("head", signature(x = "Matrix"), utils::head.matrix)
32      setMethod("head", signature(x = "Matrix"), utils:::head.matrix)  setMethod("tail", signature(x = "Matrix"), utils::tail.matrix)
33      setMethod("tail", signature(x = "Matrix"), utils:::tail.matrix)  
34  ## } else { # R 2.4.0 and newer  setMethod("drop", signature(x = "Matrix"),
35  ##     setMethod("head", signature(x = "Matrix"), utils::head.matrix)            function(x) if(all(dim(x) != 1)) x else drop(as(x, "matrix")))
 ##     setMethod("tail", signature(x = "Matrix"), utils::tail.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"),
# Line 38  Line 45 
45            function(x, ...) as.logical(as.vector(x)))            function(x, ...) as.logical(as.vector(x)))
46    
47    
48  ## Note that isSymmetric is *not* exported  ## "base" has an isSymmetric() S3-generic since R 2.3.0
 ## but that "base" has an isSymmetric() S3-generic since R 2.3.0  
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 77  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 96  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)
105  {  {
106      sparseDefault <- function(m)      sparseDefault <- function(m) prod(dim(m)) > 2*sum(isN0(as(m, "matrix")))
         prod(dim(m)) > 2*sum(as(m, "matrix") != 0)  
107    
108      i.M <- is(data, "Matrix")      i.M <- is(data, "Matrix")
109      if(is.null(sparse) && (i.M || is(data, "matrix")))      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")))
112          sparse <- sparseDefault(data)          sparse <- sparseDefault(data)
113    
114      doDN <- TRUE      doDN <- TRUE
115      if (i.M && !forceCheck) {      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((sparse && sM) || (!sparse && !sM))          if(!forceCheck && ((sparse && sM) || (!sparse && !sM)))
120              return(data)              return(data)
121          ## else : convert  dense <-> sparse -> at end          ## else : convert  dense <-> sparse -> at end
122      }      }
# Line 119  Line 125 
125              nrow <- ceiling(length(data)/ncol)              nrow <- ceiling(length(data)/ncol)
126          else if (missing(ncol))          else if (missing(ncol))
127              ncol <- ceiling(length(data)/nrow)              ncol <- ceiling(length(data)/nrow)
128          if(length(data) == 1 && data == 0 && !identical(sparse,FALSE)) {          if(length(data) == 1 && is0(data) && !identical(sparse, FALSE)) {
129              if(is.null(sparse)) sparse <- TRUE              ## Matrix(0, ...) : always sparse unless "sparse = FALSE":
130                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 135  Line 143 
143              dimnames(data) <- dimnames              dimnames(data) <- dimnames
144          }          }
145          doDN <- FALSE          doDN <- FALSE
146      }      } else if(!missing(nrow) || !missing(ncol)|| !missing(byrow))
147            warning("'nrow', 'ncol', etc, are disregarded for matrix 'data'")
148    
149      ## 'data' is now a "matrix" or "Matrix"      ## 'data' is now a "matrix" or "Matrix"
150      if (doDN && !is.null(dimnames))      if (doDN && !is.null(dimnames))
151          dimnames(data) <- dimnames          dimnames(data) <- dimnames
# Line 148  Line 158 
158      if(isDiag)      if(isDiag)
159          isDiag <- isDiagonal(data)          isDiag <- isDiagonal(data)
160    
 ### TODO: Compare with as.Matrix() and its tests in ./dgeMatrix.R  
   
161      ## Find proper matrix class 'cl'      ## Find proper matrix class 'cl'
162      cl <-      cl <-
163          if(isDiag)          if(isDiag && !isTRUE(sparse1))
164              "diagonalMatrix" # -> will automatically check for type              "diagonalMatrix" # -> will automatically check for type
165          else {          else {
166              ## consider it's type              ## consider it's type
# Line 180  Line 188 
188                    }, sep="")                    }, sep="")
189          }          }
190    
191      ## Now coerce and return      ## Can we coerce and be done?
192        if(!canCoerce(data,cl)) { ## try to coerce ``via'' virtual classes
193            if(sparse && !sM)
194                data <- as(data, "sparseMatrix")
195            else if(!sparse && !is(data, "denseMatrix"))
196                data <- as(data, "denseMatrix")
197            if(isTri && !is(data, "triangularMatrix"))
198                data <- as(data, "triangularMatrix")
199            else if(isSym && !is(data, "symmetricMatrix"))
200                data <- as(data, "symmetricMatrix")
201        }
202        ## now coerce in any case .. maybe producing sensible error message:
203      as(data, cl)      as(data, cl)
204  }  }
205    
# Line 191  Line 210 
210    
211  setMethod("%*%", signature(x = "Matrix", y = "numeric"),  setMethod("%*%", signature(x = "Matrix", y = "numeric"),
212            function(x, y) callGeneric(x, as.matrix(y)))            function(x, y) callGeneric(x, as.matrix(y)))
   
213  setMethod("%*%", signature(x = "numeric", y = "Matrix"),  setMethod("%*%", signature(x = "numeric", y = "Matrix"),
214            function(x, y) callGeneric(rbind(x), y))            function(x, y) callGeneric(matrix(x, nrow = 1, byrow=TRUE), y))
215    
216    setMethod("%*%", signature(x = "Matrix", y = "matrix"),
217              function(x, y) callGeneric(x, Matrix(y)))
218    setMethod("%*%", signature(x = "matrix", y = "Matrix"),
219              function(x, y) callGeneric(Matrix(x), y))
220    
221    
222  setMethod("crossprod", signature(x = "Matrix", y = "numeric"),  setMethod("crossprod", signature(x = "Matrix", y = "numeric"),
223            function(x, y = NULL) callGeneric(x, as.matrix(y)))            function(x, y = NULL) callGeneric(x, as.matrix(y)))
224  setMethod("crossprod", signature(x = "numeric", y = "Matrix"),  setMethod("crossprod", signature(x = "numeric", y = "Matrix"),
225            function(x, y = NULL)  callGeneric(as.matrix(x), y))            function(x, y = NULL)  callGeneric(as.matrix(x), y))
226    
227    setMethod("crossprod", signature(x = "Matrix", y = "matrix"),
228              function(x, y = NULL) callGeneric(x, Matrix(y)))
229    setMethod("crossprod", signature(x = "matrix", y = "Matrix"),
230              function(x, y = NULL) callGeneric(Matrix(x), y))
231    
232  ## The as.matrix() promotion seems illogical to MM,  ## The as.matrix() promotion seems illogical to MM,
233  ## but is according to help(tcrossprod, package = "base") :  ## but is according to help(tcrossprod, package = "base") :
234  setMethod("tcrossprod", signature(x = "Matrix", y = "numeric"),  setMethod("tcrossprod", signature(x = "Matrix", y = "numeric"),
235            function(x, y = NULL) callGeneric(x, as.matrix(y)))            function(x, y = NULL) callGeneric(x, as.matrix(y)))
236  setMethod("tcrossprod", signature(x = "numeric", y = "Matrix"),  setMethod("tcrossprod", signature(x = "numeric", y = "Matrix"),
237            function(x, y = NULL)  callGeneric(as.matrix(x), y))            function(x, y = NULL)  callGeneric(as.matrix(x), y))
238    setMethod("tcrossprod", signature(x = "Matrix", y = "matrix"),
239              function(x, y = NULL) callGeneric(x, Matrix(y)))
240    setMethod("tcrossprod", signature(x = "matrix", y = "Matrix"),
241              function(x, y = NULL) callGeneric(Matrix(x), y))
242    
243    ## maybe not 100% optimal, but elegant:
244    setMethod("solve", signature(a = "Matrix", b = "missing"),
245              function(a, b, ...) solve(a, Diagonal(nrow(a))))
246    
247  setMethod("solve", signature(a = "Matrix", b = "numeric"),  setMethod("solve", signature(a = "Matrix", b = "numeric"),
248            function(a, b, ...) callGeneric(a, as.matrix(b)))            function(a, b, ...) callGeneric(a, Matrix(b)))
249    setMethod("solve", signature(a = "Matrix", b = "matrix"),
250              function(a, b, ...) callGeneric(a, Matrix(b)))
251    setMethod("solve", signature(a = "matrix", b = "Matrix"),
252              function(a, b, ...) callGeneric(Matrix(a), b))
253    
254    ## when no sub-class method is found, bail out
255    setMethod("solve", signature(a = "Matrix", b = "Matrix"),
256              function(a, b, ...) .bail.out.2("solve", class(a), class(b)))
257    
258  ## bail-out methods in order to get better error messages  ## bail-out methods in order to get better error messages
259  setMethod("%*%", signature(x = "Matrix", y = "Matrix"),  setMethod("%*%", signature(x = "Matrix", y = "Matrix"),
# Line 235  Line 280 
280  setMethod("kronecker", signature(X = "Matrix", Y = "ANY",  setMethod("kronecker", signature(X = "Matrix", Y = "ANY",
281                                   FUN = "ANY", make.dimnames = "ANY"),                                   FUN = "ANY", make.dimnames = "ANY"),
282            function(X, Y, FUN, make.dimnames, ...) {            function(X, Y, FUN, make.dimnames, ...) {
283                  if(is(X, "sparseMatrix"))
284                      warning("using slow kronecker() method")
285                X <- as(X, "matrix") ; Matrix(callGeneric()) })                X <- as(X, "matrix") ; Matrix(callGeneric()) })
286    
287  setMethod("kronecker", signature(X = "ANY", Y = "Matrix",  setMethod("kronecker", signature(X = "ANY", Y = "Matrix",
288                                   FUN = "ANY", make.dimnames = "ANY"),                                   FUN = "ANY", make.dimnames = "ANY"),
289            function(X, Y, FUN, make.dimnames, ...) {            function(X, Y, FUN, make.dimnames, ...) {
290                  if(is(Y, "sparseMatrix"))
291                      warning("using slow kronecker() method")
292                Y <- as(Y, "matrix") ; Matrix(callGeneric()) })                Y <- as(Y, "matrix") ; Matrix(callGeneric()) })
293    
294    
295    ## FIXME: All of these should never be called
296    setMethod("chol", signature(x = "Matrix"),
297              function(x, pivot = FALSE) .bail.out.1(.Generic, class(x)))
298    setMethod("determinant", signature(x = "Matrix"),
299              function(x, logarithm = TRUE) .bail.out.1(.Generic, class(x)))
300    
301  setMethod("diag", signature(x = "Matrix"),  setMethod("diag", signature(x = "Matrix"),
302            function(x, nrow, ncol) .bail.out.1(.Generic, class(x)))            function(x, nrow, ncol) .bail.out.1(.Generic, class(x)))
303  setMethod("t", signature(x = "Matrix"),  setMethod("t", signature(x = "Matrix"),
304            function(x) .bail.out.1(.Generic, class(x)))            function(x) .bail.out.1(.Generic, class(x)))
305    
306  ## Group Methods  setMethod("norm", signature(x = "Matrix", type = "character"),
307  setMethod("+", signature(e1 = "Matrix", e2 = "missing"), function(e1) e1)            function(x, type, ...) .bail.out.1(.Generic, class(x)))
308  ## "fallback":  setMethod("rcond", signature(x = "Matrix", type = "character"),
309  setMethod("-", signature(e1 = "Matrix", e2 = "missing"),            function(x, type, ...) .bail.out.1(.Generic, class(x)))
310            function(e1) {  
311                warning("inefficient method used for \"- e1\"")  
312                0-e1  ## for all :
313    setMethod("norm", signature(x = "ANY", type = "missing"),
314              function(x, type, ...) norm(x, type = "O", ...))
315    setMethod("rcond", signature(x = "ANY", type = "missing"),
316              function(x, type, ...) rcond(x, type = "O", ...))
317    
318    
319    
320    
321    
322    ## MM: More or less "Cut & paste" from
323    ## --- diff.default() from  R/src/library/base/R/diff.R :
324    setMethod("diff", signature(x = "Matrix"),
325              function(x, lag = 1, differences = 1, ...) {
326                  if (length(lag) > 1 || length(differences) > 1 ||
327                      lag < 1 || differences < 1)
328                      stop("'lag' and 'differences' must be integers >= 1")
329                  xlen <- nrow(x)
330                  if (lag * differences >= xlen)
331                      return(x[,FALSE][0])  # empty of proper mode
332    
333                  i1 <- -1:-lag
334                  for (i in 1:differences)
335                      x <- x[i1, , drop = FALSE] -
336                          x[-nrow(x):-(nrow(x)-lag+1), , drop = FALSE]
337                  x
338            })            })
339    
340  ## bail-outs:  setMethod("image", "Matrix",
341  setMethod("Compare", signature(e1 = "Matrix", e2 = "Matrix"),            function(x, ...) { # coercing to sparse is not inefficient,
342            function(e1, e2) {                ##               since we need 'i' and 'j' for levelplot()
343                d <- dimCheck(e1,e2)                x <- as(as(x, "sparseMatrix"), "dMatrix")
344                .bail.out.2(.Generic, class(e1), class(e2))                callGeneric()
345            })            })
 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)))  
346    
347    
348    ## Group Methods
349    
350    ##-> see ./Ops.R
351    ##         ~~~~~
352    ## For all  non-dMatrix objects, and note that  "all" and "any" have their own
353    setMethod("Summary", signature(x = "Matrix", na.rm = "ANY"),
354              function(x, ..., na.rm)
355              callGeneric(as(x,"dMatrix"), ..., na.rm = na.rm))
356    
357    
358  ### --------------------------------------------------------------------------  ### --------------------------------------------------------------------------
359  ###  ###
# Line 280  Line 366 
366  ## "x[]":  ## "x[]":
367  setMethod("[", signature(x = "Matrix",  setMethod("[", signature(x = "Matrix",
368                           i = "missing", j = "missing", drop = "ANY"),                           i = "missing", j = "missing", drop = "ANY"),
369            function (x, i, j, drop) x)            function (x, i, j, ..., drop) x)
370    
371  ## missing 'drop' --> 'drop = TRUE'  ## missing 'drop' --> 'drop = TRUE'
372  ##                     -----------  ##                     -----------
373  ## select rows  ## select rows
374  setMethod("[", signature(x = "Matrix", i = "index", j = "missing",  setMethod("[", signature(x = "Matrix", i = "index", j = "missing",
375                           drop = "missing"),                           drop = "missing"),
376            function(x,i,j, drop) callGeneric(x, i=i, drop= TRUE))            function(x,i,j, ..., drop) {
377                  if(nargs() == 1) { ## e.g. M[0] , M[TRUE],  M[1:2]
378                      if(any(i)) as.vector(x)[i] else as.vector(x[1,1])[FALSE]
379                  } else callGeneric(x, i=i, drop= TRUE)})
380    
381  ## select columns  ## select columns
382  setMethod("[", signature(x = "Matrix", i = "missing", j = "index",  setMethod("[", signature(x = "Matrix", i = "missing", j = "index",
383                           drop = "missing"),                           drop = "missing"),
384            function(x,i,j, drop) callGeneric(x, j=j, drop= TRUE))            function(x,i,j, ..., drop) callGeneric(x, j=j, drop= TRUE))
385  setMethod("[", signature(x = "Matrix", i = "index", j = "index",  setMethod("[", signature(x = "Matrix", i = "index", j = "index",
386                           drop = "missing"),                           drop = "missing"),
387            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))
388    
389  ## bail out if any of (i,j,drop) is "non-sense"  ## bail out if any of (i,j,drop) is "non-sense"
390  setMethod("[", signature(x = "Matrix", i = "ANY", j = "ANY", drop = "ANY"),  setMethod("[", signature(x = "Matrix", i = "ANY", j = "ANY", drop = "ANY"),
391            function(x,i,j, drop)            function(x,i,j, ..., drop)
392            stop("invalid or not-yet-implemented 'Matrix' subsetting"))            stop("invalid or not-yet-implemented 'Matrix' subsetting"))
393    
394  ##  "logical *vector* indexing, such as  M [ M >= 10 ] :  ## logical indexing, such as M[ M >= 7 ] *BUT* also M[ M[,1] >= 3,],
395  setMethod("[", signature(x = "Matrix", i = "lMatrix", j = "missing",  ## The following is *both* for    M [ <logical>   ]
396                           drop = "ANY"),  ##                 and also for   M [ <logical> , ]
397            function (x, i, j, drop) {  .M.sub.i.logical <- function (x, i, j, ..., drop)
398    {
399        nA <- nargs()
400        if(nA == 2) { ##  M [ M >= 7 ]
401            ## FIXME: when both 'x' and 'i' are sparse, this can be very inefficient
402                as(x, geClass(x))@x[as.vector(i)]                as(x, geClass(x))@x[as.vector(i)]
403                ## -> error when lengths don't match                ## -> error when lengths don't match
404            })      } else if(nA == 3) { ##  M [ M[,1, drop=FALSE] >= 7, ]
405            stop("not-yet-implemented 'Matrix' subsetting") ## FIXME
406    
407  ## FIXME: The following is good for    M [ <logical>   ]      } else stop("nargs() = ", nA,
408  ##        *BUT* it also triggers for   M [ <logical> , ] where it is *WRONG*                  ".  Extraneous illegal arguments inside '[ .. ]' (i.logical)?")
409  ##       using nargs() does not help: it gives '3' for both cases  }
410  if(FALSE)  setMethod("[", signature(x = "Matrix", i = "lMatrix", j = "missing",
411                             drop = "ANY"),
412              .M.sub.i.logical)
413  setMethod("[", signature(x = "Matrix", i = "logical", j = "missing",  setMethod("[", signature(x = "Matrix", i = "logical", j = "missing",
414                           drop = "ANY"),                           drop = "ANY"),
415            function (x, i, j, drop) {            .M.sub.i.logical)
416                ## DEBUG  
               cat("[(Matrix,i,..): nargs=", nargs(),"\n")  
               as(x, geClass(x))@x[i] })  
417    
418    ## A[ ij ]  where ij is (i,j) 2-column matrix :
419    .M.sub.i.2col <- function (x, i, j, ..., drop)
420    {
421        nA <- nargs()
422        if(nA == 2) { ##  M [ cbind(ii,jj) ]
423            if(!is.integer(nc <- ncol(i)))
424                stop("'i' has no integer column number",
425                     " should never happen; please report")
426            if(is.logical(i))
427                return(.M.sub.i.logical(x,i,j,drop))
428            else if(!is.numeric(i) || nc != 2)
429                stop("such indexing must be by logical or 2-column numeric matrix")
430            m <- nrow(i)
431            if(m == 0) return(vector(mode = .type.kind[.M.kind(x)]))
432            ## else
433            i1 <- i[,1]
434            i2 <- i[,2]
435            ## potentially inefficient -- FIXME --
436            unlist(lapply(seq_len(m), function(j) x[i1[j], i2[j]]))
437    
438  ## "FIXME:"      } else stop("nargs() = ", nA,
439  ## How can we get at   A[ ij ]  where ij is (i,j) 2-column matrix?                  ".  Extraneous illegal arguments inside '[ .. ]' (i.2col)?")
440  ##  and                A[ LL ]  where LL is a logical *vector*  }
441  ## -> [.data.frame uses nargs() - can we do this in the *generic* ?  setMethod("[", signature(x = "Matrix", i = "matrix", j = "missing"),# drop="ANY"
442              .M.sub.i.2col)
443    
444    
445  ### "[<-" : -----------------  ### "[<-" : -----------------
# Line 333  Line 448 
448  setReplaceMethod("[", signature(x = "Matrix", i = "missing", j = "missing",  setReplaceMethod("[", signature(x = "Matrix", i = "missing", j = "missing",
449                                  value = "ANY"),## double/logical/...                                  value = "ANY"),## double/logical/...
450            function (x, value) {            function (x, value) {
451                x@x <- value                ## Fails for 'nMatrix' ... FIXME : make sure have method there
452                  x@x <- rep(value, length = length(x@x))
453                validObject(x)# check if type and lengths above match                validObject(x)# check if type and lengths above match
454                x                x
455            })            })
456    
457  ## Method for all 'Matrix' kinds (rather than incomprehensible error messages);  ## A[ ij ] <- value,  where ij is (i,j) 2-column matrix :
458    ## ----------------
459    ## The cheap general method --- FIXME: provide special ones; done for Tsparse..
460    ## NOTE:  need '...' below such that setMethod() does
461    ##        not use .local() such that nargs() will work correctly:
462    .M.repl.i.2col <- function (x, i, j, ..., value)
463    {
464        nA <- nargs()
465        if(nA == 3) { ##  M [ cbind(ii,jj) ] <- value
466            if(!is.integer(nc <- ncol(i)))
467                stop("'i' has no integer column number",
468                     " should never happen; please report")
469            else if(!is.numeric(i) || nc != 2)
470                stop("such indexing must be by logical or 2-column numeric matrix")
471            if(is.logical(i)) {
472                message(".M.repl.i.2col(): drop 'matrix' case ...")
473                i <- c(i) # drop "matrix"
474                return( callNextMethod() )
475            }
476            if(!is.integer(i)) storage.mode(i) <- "integer"
477            if(any(i < 0))
478                stop("negative values are not allowed in a matrix subscript")
479            if(any(is.na(i)))
480                stop("NAs are not allowed in subscripted assignments")
481            if(any(i0 <- (i == 0))) # remove them
482                i <- i[ - which(i0, arr.ind = TRUE)[,"row"], ]
483            ## now have integer i >= 1
484            m <- nrow(i)
485            ## mod.x <- .type.kind[.M.kind(x)]
486            if(length(value) > 0 && m %% length(value) != 0)
487                warning("number of items to replace is not a multiple of replacement length")
488            ## recycle:
489            value <- rep(value, length = m)
490            i1 <- i[,1]
491            i2 <- i[,2]
492            ## inefficient -- FIXME -- (also loses "symmetry" unnecessarily)
493            for(k in seq_len(m))
494                x[i1[k], i2[k]] <- value[k]
495    
496            x
497        } else stop("nargs() = ", nA,
498                    ".  Extraneous illegal arguments inside '[ .. ]' ?")
499    }
500    
501    setReplaceMethod("[", signature(x = "Matrix", i = "matrix", j = "missing",
502                                    value = "replValue"),
503              .M.repl.i.2col)
504    
505    
506    setReplaceMethod("[", signature(x = "Matrix", i = "missing", j = "ANY",
507                                    value = "Matrix"),
508                     function (x, i, j, ..., value)
509                     callGeneric(x=x, j=j, value = as.vector(value)))
510    
511    setReplaceMethod("[", signature(x = "Matrix", i = "ANY", j = "missing",
512                                    value = "Matrix"),
513                     function (x, i, j, ..., value)
514                     callGeneric(x=x, i=i, value = as.vector(value)))
515    
516    setReplaceMethod("[", signature(x = "Matrix", i = "ANY", j = "ANY",
517                                    value = "Matrix"),
518                     function (x, i, j, ..., value)
519                     callGeneric(x=x, i=i, j=j, value = as.vector(value)))
520    
521    setReplaceMethod("[", signature(x = "Matrix", i = "missing", j = "ANY",
522                                    value = "matrix"),
523                     function (x, i, j, ..., value)
524                     callGeneric(x=x, j=j, value = c(value)))
525    
526    setReplaceMethod("[", signature(x = "Matrix", i = "ANY", j = "missing",
527                                    value = "matrix"),
528                     function (x, i, j, ..., value)
529                     callGeneric(x=x, i=i, value = c(value)))
530    
531    setReplaceMethod("[", signature(x = "Matrix", i = "ANY", j = "ANY",
532                                    value = "matrix"),
533                     function (x, i, j, value)
534                     callGeneric(x=x, i=i, j=j, value = c(value)))
535    
536  ## (ANY,ANY,ANY) is used when no `real method' is implemented :  ## (ANY,ANY,ANY) is used when no `real method' is implemented :
537  setReplaceMethod("[", signature(x = "Matrix", i = "ANY", j = "ANY",  setReplaceMethod("[", signature(x = "Matrix", i = "ANY", j = "ANY",
538                                  value = "ANY"),                                  value = "ANY"),
539            function (x, i, j, value) {            function (x, i, j, value) {
540                if(!is.atomic(value))                if(!is.atomic(value))
541                    stop("RHS 'value' must match matrix class ", class(x))                    stop(sprintf("RHS 'value' (class %s) matches 'ANY', but must match matrix class %s",
542                                   class(value),class(x)))
543                else stop("not-yet-implemented 'Matrix[<-' method")                else stop("not-yet-implemented 'Matrix[<-' method")
544            })            })
   
   
 ## 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.1455  
changed lines
  Added in v.2062

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