SCM

SCM Repository

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

Annotation of /pkg/R/Matrix.R

Parent Directory Parent Directory | Revision Log Revision Log


Revision 2255 - (view) (download)

1 : maechler 607 #### Toplevel ``virtual'' class "Matrix"
2 :    
3 : maechler 1331
4 :     ### Virtual coercions -- via smart "helpers" (-> ./Auxiliaries.R)
5 :    
6 : maechler 1799 setAs("Matrix", "sparseMatrix", function(from) as(from, "CsparseMatrix"))
7 :     setAs("Matrix", "CsparseMatrix", function(from) as_Csparse(from))
8 : maechler 1331 setAs("Matrix", "denseMatrix", function(from) as_dense(from))
9 :    
10 : maechler 1799 ## Maybe TODO:
11 :     ## setAs("Matrix", "nMatrix", function(from) ....)
12 :    
13 : maechler 1618 ## Most of these work; this is a last resort:
14 : maechler 1548 setAs(from = "Matrix", to = "matrix", # do *not* call base::as.matrix() here:
15 :     function(from) .bail.out.2("coerce", class(from), class(to)))
16 : maechler 1618 setAs(from = "matrix", to = "Matrix", function(from) Matrix(from))
17 : maechler 1548
18 : maechler 956 ## ## probably not needed eventually:
19 :     ## setAs(from = "ddenseMatrix", to = "matrix",
20 :     ## function(from) {
21 :     ## if(length(d <- dim(from)) != 2) stop("dim(.) has not length 2")
22 :     ## array(from@x, dim = d, dimnames = dimnames(from))
23 :     ## })
24 : maechler 607
25 : maechler 676 ## should propagate to all subclasses:
26 : maechler 658 setMethod("as.matrix", signature(x = "Matrix"), function(x) as(x, "matrix"))
27 : maechler 956 ## for 'Matrix' objects, as.array() should be equivalent:
28 :     setMethod("as.array", signature(x = "Matrix"), function(x) as(x, "matrix"))
29 : maechler 658
30 : maechler 1347 ## head and tail apply to all Matrix objects for which subscripting is allowed:
31 : maechler 1513 setMethod("head", signature(x = "Matrix"), utils::head.matrix)
32 :     setMethod("tail", signature(x = "Matrix"), utils::tail.matrix)
33 : maechler 1390
34 : maechler 1751 setMethod("drop", signature(x = "Matrix"),
35 :     function(x) if(all(dim(x) != 1)) x else drop(as(x, "matrix")))
36 :    
37 : maechler 956 ## slow "fall back" method {subclasses should have faster ones}:
38 :     setMethod("as.vector", signature(x = "Matrix", mode = "missing"),
39 : mmaechler 2175 function(x, mode) as.vector(as(x, "matrix"), mode))
40 : maechler 956
41 : maechler 1389 ## 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 : maechler 956
47 : mmaechler 2175 setMethod("mean", signature(x = "Matrix"),
48 :     function(x, trim = 0, ...) ## TODO: provide 'sparseMatrix method
49 :     if(is0(trim)) sum(x, ...) / length(x)
50 :     else mean(as.numeric(x), ...))
51 :    
52 : maechler 2096 setMethod("cov2cor", signature(V = "Matrix"),
53 : maechler 2115 function(V) { ## was as(cov2cor(as(V, "matrix")), "dpoMatrix"))
54 :     r <- V
55 :     p <- (d <- dim(V))[1]
56 :     if(p != d[2]) stop("'V' is not a square matrix")
57 :     Is <- sqrt(1/diag(V)) # diag( 1/sigma_i )
58 :     if(any(!is.finite(Is)))
59 :     warning("diag(.) had 0 or NA entries; non-finite result is doubtful")
60 :     Is <- Diagonal(x = Is)
61 :     r <- Is %*% V %*% Is
62 :     r[cbind(1L:p,1L:p)] <- 1 # exact in diagonal
63 :     as(forceSymmetric(r), "dpoMatrix")
64 :     })
65 : maechler 1389
66 : maechler 1467 ## "base" has an isSymmetric() S3-generic since R 2.3.0
67 : maechler 1108 setMethod("isSymmetric", signature(object = "symmetricMatrix"),
68 : maechler 2112 function(object, ...) TRUE)
69 : maechler 1108 setMethod("isSymmetric", signature(object = "triangularMatrix"),
70 : maechler 2112 ## TRUE iff diagonal:
71 :     function(object, ...) isDiagonal(object))
72 : maechler 1189
73 : maechler 1238 setMethod("isTriangular", signature(object = "matrix"), isTriMat)
74 :    
75 : maechler 1174 setMethod("isDiagonal", signature(object = "matrix"), .is.diagonal)
76 : maechler 886
77 : maechler 2112 ## The "catch all" methods -- far from optimal:
78 :     setMethod("symmpart", signature(x = "Matrix"),
79 :     function(x) as((x + t(x))/2, "symmetricMatrix"))
80 :     setMethod("skewpart", signature(x = "Matrix"),
81 :     function(x) (x - t(x))/2)
82 : maechler 1174
83 : maechler 2112 ## FIXME: do this (similarly as for "ddense.." in C
84 :     setMethod("symmpart", signature(x = "matrix"), function(x) (x + t(x))/2)
85 :     setMethod("skewpart", signature(x = "matrix"), function(x) (x - t(x))/2)
86 : maechler 1174
87 : maechler 2112
88 :    
89 :    
90 : maechler 579 setMethod("dim", signature(x = "Matrix"),
91 : maechler 698 function(x) x@Dim, valueClass = "integer")
92 : maechler 1705
93 : maechler 1738 setMethod("length", "Matrix", function(x) prod(dim(x)))
94 :    
95 : maechler 579 setMethod("dimnames", signature(x = "Matrix"), function(x) x@Dimnames)
96 : maechler 1705
97 :    
98 : maechler 607 ## not exported but used more than once for "dimnames<-" method :
99 :     ## -- or do only once for all "Matrix" classes ??
100 :     dimnamesGets <- function (x, value) {
101 :     d <- dim(x)
102 :     if (!is.list(value) || length(value) != 2 ||
103 : maechler 698 !(is.null(v1 <- value[[1]]) || length(v1) == d[1]) ||
104 :     !(is.null(v2 <- value[[2]]) || length(v2) == d[2]))
105 :     stop(sprintf("invalid dimnames given for '%s' object", class(x)))
106 : maechler 607 x@Dimnames <- list(if(!is.null(v1)) as.character(v1),
107 : maechler 698 if(!is.null(v2)) as.character(v2))
108 : maechler 607 x
109 :     }
110 :     setMethod("dimnames<-", signature(x = "Matrix", value = "list"),
111 : maechler 698 dimnamesGets)
112 : maechler 579
113 : mmaechler 2193 setMethod("dimnames<-", signature(x = "Matrix", value = "NULL"),
114 :     function(x, value) {
115 :     message("dimnames(.) <- NULL: translated to \n",
116 :     "dimnames(.) <- list(NULL,NULL) <==> unname(.)")
117 :     x@Dimnames <- list(NULL,NULL)
118 :     x
119 :     })
120 :    
121 : maechler 658 setMethod("unname", signature("Matrix", force="missing"),
122 : maechler 698 function(obj) { obj@Dimnames <- list(NULL,NULL); obj})
123 : maechler 607
124 : maechler 1705 setMethod("all", signature(x = "Matrix"),
125 : maechler 2015 function(x, ..., na.rm)
126 :     callGeneric(as(x, "lMatrix"), ..., na.rm=na.rm))
127 :    
128 : maechler 1705 setMethod("any", signature(x = "Matrix"),
129 : maechler 2015 function(x, ..., na.rm)
130 :     callGeneric(as(x, "lMatrix"), ..., na.rm=na.rm))
131 : maechler 1705
132 : maechler 1832 ## NOTE: "&" and "|" are now in group "Logic" c "Ops" --> ./Ops.R
133 :     ## "!" is in ./not.R
134 : maechler 1705
135 :    
136 : maechler 2115 Matrix <- function (data = NA, nrow = 1, ncol = 1, byrow = FALSE,
137 :     dimnames = NULL, sparse = NULL, forceCheck = FALSE)
138 : bates 10 {
139 : maechler 1665 sparseDefault <- function(m) prod(dim(m)) > 2*sum(isN0(as(m, "matrix")))
140 : maechler 954
141 :     i.M <- is(data, "Matrix")
142 : maechler 2043 if(!i.M && inherits(data, "table")) # special treatment
143 :     class(data) <- "matrix" # "matrix" first for S4 dispatch
144 : maechler 1618 if(is.null(sparse1 <- sparse) && (i.M || is(data, "matrix")))
145 : maechler 1174 sparse <- sparseDefault(data)
146 : maechler 2115 sM <- FALSE
147 : maechler 1455 doDN <- TRUE
148 : maechler 1551 if (i.M) {
149 : maechler 1751 if(!missing(nrow) || !missing(ncol)|| !missing(byrow))
150 :     warning("'nrow', 'ncol', etc, are disregarded when 'data' is \"Matrix\" already")
151 : maechler 1174 sM <- is(data,"sparseMatrix")
152 : maechler 1551 if(!forceCheck && ((sparse && sM) || (!sparse && !sM)))
153 : maechler 1174 return(data)
154 :     ## else : convert dense <-> sparse -> at end
155 : maechler 954 }
156 :     else if (!is.matrix(data)) { ## cut & paste from "base::matrix" :
157 : maechler 698 if (missing(nrow))
158 :     nrow <- ceiling(length(data)/ncol)
159 :     else if (missing(ncol))
160 :     ncol <- ceiling(length(data)/nrow)
161 : maechler 1618 if(length(data) == 1 && is0(data) && !identical(sparse, FALSE)) {
162 : maechler 2115 ## Matrix(0, ...) : always sparse unless "sparse = FALSE":
163 : maechler 1618 if(is.null(sparse)) sparse1 <- sparse <- TRUE
164 : maechler 2115 i.M <- sM <- TRUE
165 :     isSym <- nrow == ncol
166 : maechler 1315 ## will be sparse: do NOT construct full matrix!
167 : maechler 2115 data <- new(paste(if(is.numeric(data)) "d" else
168 :     if(is.logical(data)) "l" else
169 :     stop("invalid 'data'"),
170 :     if(isSym) "s" else "g", "CMatrix", sep=''),
171 :     p = rep.int(0L, ncol+1L),
172 : maechler 1315 Dim = as.integer(c(nrow,ncol)),
173 : maechler 1332 Dimnames = if(is.null(dimnames)) list(NULL,NULL)
174 :     else dimnames)
175 : maechler 2081 } else { ## normal case - using .Internal() to avoid more copying
176 :     if(getRversion() >= "2.7.0")
177 :     data <- .Internal(matrix(data, nrow, ncol, byrow, dimnames))
178 :     else {
179 :     data <- .Internal(matrix(data, nrow, ncol, byrow))
180 :     dimnames(data) <- dimnames
181 :     }
182 : maechler 1315 if(is.null(sparse))
183 :     sparse <- sparseDefault(data)
184 :     }
185 : maechler 1455 doDN <- FALSE
186 : maechler 1751 } else if(!missing(nrow) || !missing(ncol)|| !missing(byrow))
187 : maechler 1747 warning("'nrow', 'ncol', etc, are disregarded for matrix 'data'")
188 :    
189 : maechler 1455 ## 'data' is now a "matrix" or "Matrix"
190 :     if (doDN && !is.null(dimnames))
191 : maechler 1189 dimnames(data) <- dimnames
192 : maechler 954
193 : maechler 1174 ## check for symmetric / triangular / diagonal :
194 :     isSym <- isSymmetric(data)
195 :     if((isTri <- !isSym))
196 :     isTri <- isTriangular(data)
197 :     isDiag <- isSym # cannot be diagonal if it isn't symmetric
198 :     if(isDiag)
199 : maechler 2115 isDiag <- !isTRUE(sparse1) && isDiagonal(data)
200 : maechler 1174
201 : maechler 2115 ## try to coerce ``via'' virtual classes
202 :     if(isDiag) { ## diagonal is preferred to sparse !
203 :     data <- as(data, "diagonalMatrix")
204 :     isSym <- FALSE
205 :     } else if(sparse && !sM)
206 :     data <- as(data, "sparseMatrix")
207 :     else if(!sparse) {
208 :     if(i.M) { ## data is 'Matrix'
209 :     if(!is(data, "denseMatrix"))
210 :     data <- as(data, "denseMatrix")
211 :     } else { ## data is "matrix" (and result "dense" -> go via "general"
212 :     ctype <- typeof(data)
213 :     if (ctype == "complex")
214 : maechler 1174 stop("complex matrices not yet implemented in Matrix package")
215 : maechler 2115 if (ctype == "integer") ## integer Matrices not yet implemented
216 :     storage.mode(data) <- "double"
217 :     data <- new(paste(.M.kind(data), "geMatrix", sep=''),
218 :     Dim = dim(data),
219 :     Dimnames = .M.DN(data),
220 :     x = c(data))
221 : maechler 1174 }
222 : maechler 2115 }
223 : maechler 1174
224 : maechler 2115 if(isTri && !is(data, "triangularMatrix")) {
225 :     data <- if(attr(isTri,"kind") == "L") tril(data) else triu(data)
226 :     #was as(data, "triangularMatrix")
227 :     } else if(isSym && !is(data, "symmetricMatrix"))
228 :     data <- forceSymmetric(data) #was as(data, "symmetricMatrix")
229 :    
230 :     data
231 : bates 10 }
232 :    
233 : bates 683 ## Methods for operations where one argument is numeric
234 : maechler 512
235 : maechler 698 ## Using as.matrix() and rbind()
236 :     ## in order to get dimnames from names {at least potentially}:
237 :    
238 : bates 683 setMethod("%*%", signature(x = "Matrix", y = "numeric"),
239 : maechler 698 function(x, y) callGeneric(x, as.matrix(y)))
240 : bates 683 setMethod("%*%", signature(x = "numeric", y = "Matrix"),
241 : maechler 1660 function(x, y) callGeneric(matrix(x, nrow = 1, byrow=TRUE), y))
242 : bates 683
243 : maechler 2036 setMethod("%*%", signature(x = "Matrix", y = "matrix"),
244 :     function(x, y) callGeneric(x, Matrix(y)))
245 :     setMethod("%*%", signature(x = "matrix", y = "Matrix"),
246 :     function(x, y) callGeneric(Matrix(x), y))
247 :    
248 :    
249 : bates 683 setMethod("crossprod", signature(x = "Matrix", y = "numeric"),
250 : maechler 698 function(x, y = NULL) callGeneric(x, as.matrix(y)))
251 : bates 683 setMethod("crossprod", signature(x = "numeric", y = "Matrix"),
252 : maechler 1331 function(x, y = NULL) callGeneric(as.matrix(x), y))
253 : bates 683
254 : maechler 2036 setMethod("crossprod", signature(x = "Matrix", y = "matrix"),
255 : maechler 2039 function(x, y = NULL) callGeneric(x, Matrix(y)))
256 : maechler 2036 setMethod("crossprod", signature(x = "matrix", y = "Matrix"),
257 : maechler 2039 function(x, y = NULL) callGeneric(Matrix(x), y))
258 : maechler 2036
259 : maechler 1331 ## The as.matrix() promotion seems illogical to MM,
260 :     ## but is according to help(tcrossprod, package = "base") :
261 :     setMethod("tcrossprod", signature(x = "Matrix", y = "numeric"),
262 :     function(x, y = NULL) callGeneric(x, as.matrix(y)))
263 :     setMethod("tcrossprod", signature(x = "numeric", y = "Matrix"),
264 :     function(x, y = NULL) callGeneric(as.matrix(x), y))
265 : maechler 2036 setMethod("tcrossprod", signature(x = "Matrix", y = "matrix"),
266 : maechler 2039 function(x, y = NULL) callGeneric(x, Matrix(y)))
267 : maechler 2036 setMethod("tcrossprod", signature(x = "matrix", y = "Matrix"),
268 : maechler 2039 function(x, y = NULL) callGeneric(Matrix(x), y))
269 : maechler 1331
270 : maechler 2043 ## maybe not 100% optimal, but elegant:
271 : maechler 1665 setMethod("solve", signature(a = "Matrix", b = "missing"),
272 :     function(a, b, ...) solve(a, Diagonal(nrow(a))))
273 :    
274 : bates 683 setMethod("solve", signature(a = "Matrix", b = "numeric"),
275 : maechler 2036 function(a, b, ...) callGeneric(a, Matrix(b)))
276 :     setMethod("solve", signature(a = "Matrix", b = "matrix"),
277 :     function(a, b, ...) callGeneric(a, Matrix(b)))
278 :     setMethod("solve", signature(a = "matrix", b = "Matrix"),
279 :     function(a, b, ...) callGeneric(Matrix(a), b))
280 :    
281 : mmaechler 2236 setMethod("solve", signature(a = "Matrix", b = "diagonalMatrix"),
282 :     function(a, b, ...) callGeneric(a, as(b,"CsparseMatrix")))
283 :    
284 : maechler 1659 ## when no sub-class method is found, bail out
285 : maechler 1747 setMethod("solve", signature(a = "Matrix", b = "Matrix"),
286 :     function(a, b, ...) .bail.out.2("solve", class(a), class(b)))
287 : maechler 848
288 : maechler 925 ## bail-out methods in order to get better error messages
289 :     setMethod("%*%", signature(x = "Matrix", y = "Matrix"),
290 :     function (x, y)
291 :     stop(gettextf('not-yet-implemented method for <%s> %%*%% <%s>',
292 :     class(x), class(y))))
293 : maechler 946
294 : maechler 925 setMethod("crossprod", signature(x = "Matrix", y = "ANY"),
295 : maechler 946 function (x, y = NULL) .bail.out.2(.Generic, class(x), class(y)))
296 : maechler 956 setMethod("crossprod", signature(x = "ANY", y = "Matrix"),
297 :     function (x, y = NULL) .bail.out.2(.Generic, class(x), class(y)))
298 : maechler 1331 setMethod("tcrossprod", signature(x = "Matrix", y = "ANY"),
299 :     function (x, y = NULL) .bail.out.2(.Generic, class(x), class(y)))
300 :     setMethod("tcrossprod", signature(x = "ANY", y = "Matrix"),
301 :     function (x, y = NULL) .bail.out.2(.Generic, class(x), class(y)))
302 : maechler 925
303 : maechler 1331 ## cheap fallbacks
304 :     setMethod("crossprod", signature(x = "Matrix", y = "Matrix"),
305 :     function(x, y = NULL) t(x) %*% y)
306 :     setMethod("tcrossprod", signature(x = "Matrix", y = "Matrix"),
307 :     function(x, y = NULL) x %*% t(y))
308 :    
309 : maechler 956 ## There are special sparse methods; this is a "fall back":
310 :     setMethod("kronecker", signature(X = "Matrix", Y = "ANY",
311 : maechler 1805 FUN = "ANY", make.dimnames = "ANY"),
312 :     function(X, Y, FUN, make.dimnames, ...) {
313 : maechler 1825 if(is(X, "sparseMatrix"))
314 :     warning("using slow kronecker() method")
315 : maechler 1805 X <- as(X, "matrix") ; Matrix(callGeneric()) })
316 :    
317 : maechler 956 setMethod("kronecker", signature(X = "ANY", Y = "Matrix",
318 : maechler 1805 FUN = "ANY", make.dimnames = "ANY"),
319 :     function(X, Y, FUN, make.dimnames, ...) {
320 : maechler 1825 if(is(Y, "sparseMatrix"))
321 :     warning("using slow kronecker() method")
322 : maechler 1805 Y <- as(Y, "matrix") ; Matrix(callGeneric()) })
323 : maechler 956
324 :    
325 : mmaechler 2175 setMethod("determinant", signature(x = "Matrix", logarithm = "missing"),
326 :     function(x, logarithm, ...)
327 :     determinant(x, logarithm = TRUE, ...))
328 :    
329 :     if(FALSE) { ## This is desired "in theory" - but gives
330 :     ## "The following object(s) are masked from package:base : det
331 :     ## base::det() calls [base::]determinant();
332 :     ## our det() should call our determinant() :
333 :     det <- base::det
334 :     environment(det) <- environment()## == as.environment("Matrix")
335 :     }
336 :    
337 : maechler 1654 ## FIXME: All of these should never be called
338 :     setMethod("chol", signature(x = "Matrix"),
339 : mmaechler 2175 function(x, pivot, ...) .bail.out.1(.Generic, class(x)))
340 :     setMethod("determinant", signature(x = "Matrix", logarithm = "logical"),
341 : mmaechler 2185 function(x, logarithm, ...)
342 :     determinant(as(x,"dMatrix"), logarithm=logarithm, ...))
343 : maechler 1654
344 : maechler 1315 setMethod("diag", signature(x = "Matrix"),
345 :     function(x, nrow, ncol) .bail.out.1(.Generic, class(x)))
346 : maechler 946 setMethod("t", signature(x = "Matrix"),
347 :     function(x) .bail.out.1(.Generic, class(x)))
348 : maechler 925
349 : maechler 2005 setMethod("norm", signature(x = "Matrix", type = "character"),
350 :     function(x, type, ...) .bail.out.1(.Generic, class(x)))
351 : maechler 2158 setMethod("rcond", signature(x = "Matrix", norm = "character"),
352 :     function(x, norm, ...) .bail.out.1(.Generic, class(x)))
353 : maechler 2005
354 :    
355 :     ## for all :
356 :     setMethod("norm", signature(x = "ANY", type = "missing"),
357 :     function(x, type, ...) norm(x, type = "O", ...))
358 : maechler 2158 setMethod("rcond", signature(x = "ANY", norm = "missing"),
359 :     function(x, norm, ...) rcond(x, norm = "O", ...))
360 : maechler 2005
361 :    
362 :    
363 :    
364 : mmaechler 2245 ## We want to use all.equal.numeric() *and* make sure that uses
365 :     ## not just base::as.vector but the generic with our methods:
366 :     all.equal_num <- base::all.equal.numeric ## from <R>/src/library/base/R/all.equal.R
367 :     environment(all.equal_num) <- environment()## == as.environment("Matrix")
368 : mmaechler 2255
369 :     all.equal_Mat <- function(target, current, check.attributes = TRUE, ...)
370 :     {
371 :     msg <- attr.all_Mat(target, current, check.attributes=check.attributes, ...)
372 :     if(is.list(msg)) return(msg[[1]])
373 :     ## else
374 :     r <- all.equal_num(as.vector(target), as.vector(current),
375 :     check.attributes=check.attributes, ...)
376 :     if(is.null(msg) && (r.ok <- isTRUE(r))) TRUE else c(msg, if(!r.ok) r)
377 :     }
378 : mmaechler 2245 ## The all.equal() methods for dense matrices (and fallback):
379 :     setMethod("all.equal", c(target = "Matrix", current = "Matrix"),
380 : mmaechler 2255 all.equal_Mat)
381 : mmaechler 2245 setMethod("all.equal", c(target = "Matrix", current = "ANY"),
382 : mmaechler 2255 all.equal_Mat)
383 : mmaechler 2245 setMethod("all.equal", c(target = "ANY", current = "Matrix"),
384 : mmaechler 2255 all.equal_Mat)
385 : mmaechler 2245 ## -> ./sparseMatrix.R, ./sparseVector.R have specific methods
386 : maechler 2005
387 : mmaechler 2245
388 :    
389 : maechler 1799 ## MM: More or less "Cut & paste" from
390 :     ## --- diff.default() from R/src/library/base/R/diff.R :
391 :     setMethod("diff", signature(x = "Matrix"),
392 :     function(x, lag = 1, differences = 1, ...) {
393 :     if (length(lag) > 1 || length(differences) > 1 ||
394 :     lag < 1 || differences < 1)
395 :     stop("'lag' and 'differences' must be integers >= 1")
396 :     xlen <- nrow(x)
397 :     if (lag * differences >= xlen)
398 :     return(x[,FALSE][0]) # empty of proper mode
399 :    
400 :     i1 <- -1:-lag
401 :     for (i in 1:differences)
402 :     x <- x[i1, , drop = FALSE] -
403 :     x[-nrow(x):-(nrow(x)-lag+1), , drop = FALSE]
404 :     x
405 :     })
406 :    
407 : maechler 1829 setMethod("image", "Matrix",
408 :     function(x, ...) { # coercing to sparse is not inefficient,
409 :     ## since we need 'i' and 'j' for levelplot()
410 :     x <- as(as(x, "sparseMatrix"), "dMatrix")
411 :     callGeneric()
412 :     })
413 : maechler 1799
414 : maechler 1829
415 : maechler 956 ## Group Methods
416 :    
417 : maechler 2005 ## For all non-dMatrix objects, and note that "all" and "any" have their own
418 :     setMethod("Summary", signature(x = "Matrix", na.rm = "ANY"),
419 :     function(x, ..., na.rm)
420 :     callGeneric(as(x,"dMatrix"), ..., na.rm = na.rm))
421 : maechler 1655
422 : mmaechler 2175 Summary.l <- function(x, ..., na.rm) { ## must be method directly
423 :     r <- callGeneric(as(x,"dMatrix"), ..., na.rm = na.rm)
424 :     if(!is.infinite(r) && .Generic %in% c("max", "min", "range", "sum"))
425 :     as.integer(r) else r
426 :     }
427 :     setMethod("Summary", signature(x = "lMatrix", na.rm = "ANY"), Summary.l)
428 :     setMethod("Summary", signature(x = "nMatrix", na.rm = "ANY"), Summary.l)
429 :     setMethod("Summary", signature(x = "pMatrix", na.rm = "ANY"), Summary.l)
430 : maechler 2005
431 : mmaechler 2175 ## Further, see ./Ops.R
432 :     ## ~~~~~
433 :    
434 :    
435 : maechler 871 ### --------------------------------------------------------------------------
436 :     ###
437 :     ### Subsetting "[" and
438 :     ### SubAssign "[<-" : The "missing" cases can be dealt with here, "at the top":
439 : maechler 868
440 : maechler 886 ## Using "index" for indices should allow
441 : maechler 875 ## integer (numeric), logical, or character (names!) indices :
442 :    
443 : maechler 868 ## "x[]":
444 :     setMethod("[", signature(x = "Matrix",
445 :     i = "missing", j = "missing", drop = "ANY"),
446 : maechler 2056 function (x, i, j, ..., drop) x)
447 : maechler 1225
448 : maechler 868 ## missing 'drop' --> 'drop = TRUE'
449 :     ## -----------
450 : maechler 2111 ## select rows __ or __ vector indexing:
451 : maechler 886 setMethod("[", signature(x = "Matrix", i = "index", j = "missing",
452 : maechler 868 drop = "missing"),
453 : maechler 2056 function(x,i,j, ..., drop) {
454 : maechler 2098 if(nargs() == 2) { ## e.g. M[0] , M[TRUE], M[1:2]
455 : maechler 2111 if(any(as.logical(i)) || prod(dim(x)) == 0)
456 :     ## FIXME: for *large sparse*, use sparseVector !
457 : maechler 2098 as.vector(x)[i]
458 : maechler 2111 else ## save memory (for large sparse M):
459 : maechler 2098 as.vector(x[1,1])[FALSE]
460 :     } else {
461 :     callGeneric(x, i=i, , drop=TRUE)
462 :     ## ^^
463 :     }
464 :     })
465 : maechler 1799
466 : maechler 868 ## select columns
467 : maechler 886 setMethod("[", signature(x = "Matrix", i = "missing", j = "index",
468 : maechler 868 drop = "missing"),
469 : maechler 2056 function(x,i,j, ..., drop) callGeneric(x, j=j, drop= TRUE))
470 : maechler 886 setMethod("[", signature(x = "Matrix", i = "index", j = "index",
471 : maechler 868 drop = "missing"),
472 : maechler 2056 function(x,i,j, ..., drop) callGeneric(x, i=i, j=j, drop= TRUE))
473 : maechler 868
474 : maechler 875 ## bail out if any of (i,j,drop) is "non-sense"
475 :     setMethod("[", signature(x = "Matrix", i = "ANY", j = "ANY", drop = "ANY"),
476 : maechler 2056 function(x,i,j, ..., drop)
477 : maechler 875 stop("invalid or not-yet-implemented 'Matrix' subsetting"))
478 :    
479 : maechler 1472 ## logical indexing, such as M[ M >= 7 ] *BUT* also M[ M[,1] >= 3,],
480 :     ## The following is *both* for M [ <logical> ]
481 :     ## and also for M [ <logical> , ]
482 : maechler 2056 .M.sub.i.logical <- function (x, i, j, ..., drop)
483 : maechler 1472 {
484 :     nA <- nargs()
485 :     if(nA == 2) { ## M [ M >= 7 ]
486 : maechler 2112 ## FIXME: when both 'x' and 'i' are sparse, this can be very inefficient
487 :     if(is(x, "sparseMatrix"))
488 :     message("<sparse>[ <logic> ] : .M.sub.i.logical() maybe inefficient")
489 :     toC <- geClass(x)
490 :     if(canCoerce(x, toC)) as(x, toC)@x[as.vector(i)]
491 :     else as(as(as(x, "generalMatrix"), "denseMatrix"), toC)@x[as.vector(i)]
492 : maechler 1472 ## -> error when lengths don't match
493 :     } else if(nA == 3) { ## M [ M[,1, drop=FALSE] >= 7, ]
494 :     stop("not-yet-implemented 'Matrix' subsetting") ## FIXME
495 :    
496 :     } else stop("nargs() = ", nA,
497 : maechler 2056 ". Extraneous illegal arguments inside '[ .. ]' (i.logical)?")
498 : maechler 1472 }
499 : maechler 1225 setMethod("[", signature(x = "Matrix", i = "lMatrix", j = "missing",
500 :     drop = "ANY"),
501 : maechler 1472 .M.sub.i.logical)
502 : maechler 1225 setMethod("[", signature(x = "Matrix", i = "logical", j = "missing",
503 :     drop = "ANY"),
504 : maechler 1472 .M.sub.i.logical)
505 : maechler 1225
506 :    
507 : maechler 2112 subset.ij <- function(x, ij) {
508 :     m <- nrow(ij)
509 :     if(m > 3) {
510 :     cld <- getClassDef(class(x))
511 :     sym.x <- extends(cld, "symmetricMatrix")
512 :     if(sym.x) {
513 :     W <- if(x@uplo == "U") # stored only [i,j] with i <= j
514 :     ij[,1] > ij[,2] else ij[,1] < ij[,2]
515 :     if(any(W))
516 :     ij[W,] <- ij[W, 2:1]
517 :     }
518 :     if(extends(cld, "sparseMatrix")) {
519 :     ## do something smarter:
520 : mmaechler 2203 di <- dim(x)
521 : maechler 2112 if(!extends(cld, "CsparseMatrix")) {
522 :     x <- as(x, "CsparseMatrix") # simpler; our standard
523 :     cld <- getClassDef(class(x))
524 :     }
525 :     tri.x <- extends(cld, "triangularMatrix")
526 :     if(tri.x) {
527 :     ## need these for the 'x' slot in any case
528 :     if (x@diag == "U") x <- .Call(Csparse_diagU2N, x)
529 :     ## slightly more efficient than non0.i() or non0ind():
530 :     ij.x <- .Call(compressed_non_0_ij, x, isC=TRUE)
531 :     } else { ## symmetric / general : for symmetric, only "existing"b
532 :     ij.x <- non0.i(x, cld)
533 :     }
534 :    
535 : mmaechler 2203 mi <- match(.Call(m_encodeInd, ij.x, di),
536 :     .Call(m_encodeInd, ij -1L, di), nomatch=0)
537 : maechler 2112 mmi <- mi != 0
538 :     ## Result:
539 :     ans <- vector(mode = .type.kind[.M.kindC(cld)], length = m)
540 :     ## those that are *not* zero:
541 :     ans[mi[mmi]] <-
542 :     if(extends(cld, "nsparseMatrix")) TRUE else x@x[mmi]
543 :     ans
544 :    
545 :     } else { ## non-sparse : dense
546 : maechler 2115 ##---- NEVER happens: 'denseMatrix' has its own setMethod(.) !
547 : maechler 2112 message("m[ <ij-matrix> ]: inefficiently indexing single elements")
548 :     i1 <- ij[,1]
549 :     i2 <- ij[,2]
550 : maechler 2115 ## very inefficient for large m
551 : maechler 2112 unlist(lapply(seq_len(m), function(j) x[i1[j], i2[j]]))
552 :     }
553 :     } else { # 1 <= m <= 3
554 :     i1 <- ij[,1]
555 :     i2 <- ij[,2]
556 :     unlist(lapply(seq_len(m), function(j) x[i1[j], i2[j]]))
557 :     }
558 :     }
559 :    
560 : maechler 2110 ## A[ ij ] where ij is (i,j) 2-column matrix -- but also when that is logical mat!
561 : maechler 2056 .M.sub.i.2col <- function (x, i, j, ..., drop)
562 : maechler 1673 {
563 :     nA <- nargs()
564 : maechler 2110 if(nA == 2) { ## M [ cbind(ii,jj) ] or M [ <logical matrix> ]
565 : maechler 1673 if(!is.integer(nc <- ncol(i)))
566 : maechler 2110 stop(".M.sub.i.2col(): 'i' has no integer column number;\n",
567 :     "should never happen; please report")
568 : maechler 1673 if(is.logical(i))
569 : maechler 2110 return(.M.sub.i.logical(x, i=i)) # call with 2 args!
570 : maechler 1673 else if(!is.numeric(i) || nc != 2)
571 :     stop("such indexing must be by logical or 2-column numeric matrix")
572 :     m <- nrow(i)
573 :     if(m == 0) return(vector(mode = .type.kind[.M.kind(x)]))
574 :     ## else
575 : maechler 2112 subset.ij(x, i)
576 : maechler 868
577 : maechler 1747 } else stop("nargs() = ", nA,
578 : maechler 2056 ". Extraneous illegal arguments inside '[ .. ]' (i.2col)?")
579 : maechler 1673 }
580 :     setMethod("[", signature(x = "Matrix", i = "matrix", j = "missing"),# drop="ANY"
581 :     .M.sub.i.2col)
582 : maechler 868
583 : maechler 1472
584 : maechler 871 ### "[<-" : -----------------
585 : maechler 868
586 : maechler 871 ## x[] <- value :
587 :     setReplaceMethod("[", signature(x = "Matrix", i = "missing", j = "missing",
588 : maechler 1189 value = "ANY"),## double/logical/...
589 :     function (x, value) {
590 : maechler 1615 ## Fails for 'nMatrix' ... FIXME : make sure have method there
591 : maechler 1747 x@x <- rep(value, length = length(x@x))
592 : maechler 1615 validObject(x)# check if type and lengths above match
593 :     x
594 : maechler 1189 })
595 : maechler 871
596 : maechler 1673 ## A[ ij ] <- value, where ij is (i,j) 2-column matrix :
597 : maechler 2056 ## ----------------
598 :     ## The cheap general method --- FIXME: provide special ones; done for Tsparse..
599 :     ## NOTE: need '...' below such that setMethod() does
600 :     ## not use .local() such that nargs() will work correctly:
601 :     .M.repl.i.2col <- function (x, i, j, ..., value)
602 : maechler 1673 {
603 :     nA <- nargs()
604 : maechler 2110 if(nA == 3) { ## M [ cbind(ii,jj) ] <- value or M [ Lmat ] <- value
605 : maechler 1673 if(!is.integer(nc <- ncol(i)))
606 : maechler 2110 stop(".M.repl.i.2col(): 'i' has no integer column number;\n",
607 :     "should never happen; please report")
608 : maechler 1724 else if(!is.numeric(i) || nc != 2)
609 :     stop("such indexing must be by logical or 2-column numeric matrix")
610 : maechler 1673 if(is.logical(i)) {
611 : maechler 1738 message(".M.repl.i.2col(): drop 'matrix' case ...")
612 : maechler 2110 ## c(i) : drop "matrix" to logical vector
613 :     return( callGeneric(x, i=c(i), value=value) )
614 :     }
615 : maechler 1724 if(!is.integer(i)) storage.mode(i) <- "integer"
616 :     if(any(i < 0))
617 :     stop("negative values are not allowed in a matrix subscript")
618 :     if(any(is.na(i)))
619 :     stop("NAs are not allowed in subscripted assignments")
620 :     if(any(i0 <- (i == 0))) # remove them
621 :     i <- i[ - which(i0, arr.ind = TRUE)[,"row"], ]
622 :     ## now have integer i >= 1
623 : maechler 1673 m <- nrow(i)
624 : maechler 1724 ## mod.x <- .type.kind[.M.kind(x)]
625 : maechler 1673 if(length(value) > 0 && m %% length(value) != 0)
626 :     warning("number of items to replace is not a multiple of replacement length")
627 :     ## recycle:
628 :     value <- rep(value, length = m)
629 :     i1 <- i[,1]
630 :     i2 <- i[,2]
631 : maechler 2112 if(m > 2)
632 :     message("m[ <ij-matrix> ] <- v: inefficiently treating single elements")
633 : maechler 1673 ## inefficient -- FIXME -- (also loses "symmetry" unnecessarily)
634 :     for(k in seq_len(m))
635 :     x[i1[k], i2[k]] <- value[k]
636 : maechler 1724
637 : maechler 1673 x
638 : maechler 1747 } else stop("nargs() = ", nA,
639 :     ". Extraneous illegal arguments inside '[ .. ]' ?")
640 : maechler 1673 }
641 : maechler 1724
642 : maechler 1673 setReplaceMethod("[", signature(x = "Matrix", i = "matrix", j = "missing",
643 :     value = "replValue"),
644 :     .M.repl.i.2col)
645 :    
646 : mmaechler 2207 ## Three catch-all methods ... would be very inefficient for sparse*
647 :     ## --> extra methods in ./sparseMatrix.R
648 : maechler 2062 setReplaceMethod("[", signature(x = "Matrix", i = "missing", j = "ANY",
649 : maechler 1615 value = "Matrix"),
650 : maechler 2062 function (x, i, j, ..., value)
651 : maechler 2098 callGeneric(x=x, , j=j, value = as.vector(value)))
652 : maechler 1705
653 : maechler 2062 setReplaceMethod("[", signature(x = "Matrix", i = "ANY", j = "missing",
654 :     value = "Matrix"),
655 :     function (x, i, j, ..., value)
656 : maechler 2098 callGeneric(x=x, i=i, , value = as.vector(value)))
657 : maechler 2056
658 : maechler 1705 setReplaceMethod("[", signature(x = "Matrix", i = "ANY", j = "ANY",
659 :     value = "Matrix"),
660 : maechler 2062 function (x, i, j, ..., value)
661 : maechler 1615 callGeneric(x=x, i=i, j=j, value = as.vector(value)))
662 : maechler 1705
663 : mmaechler 2207
664 : maechler 2062 setReplaceMethod("[", signature(x = "Matrix", i = "missing", j = "ANY",
665 :     value = "matrix"),
666 :     function (x, i, j, ..., value)
667 : maechler 2098 callGeneric(x=x, , j=j, value = c(value)))
668 : maechler 2062
669 :     setReplaceMethod("[", signature(x = "Matrix", i = "ANY", j = "missing",
670 :     value = "matrix"),
671 :     function (x, i, j, ..., value)
672 : maechler 2098 callGeneric(x=x, i=i, , value = c(value)))
673 : maechler 2062
674 : maechler 1615 setReplaceMethod("[", signature(x = "Matrix", i = "ANY", j = "ANY",
675 :     value = "matrix"),
676 :     function (x, i, j, value)
677 :     callGeneric(x=x, i=i, j=j, value = c(value)))
678 :    
679 : maechler 1189 ## (ANY,ANY,ANY) is used when no `real method' is implemented :
680 : maechler 871 setReplaceMethod("[", signature(x = "Matrix", i = "ANY", j = "ANY",
681 :     value = "ANY"),
682 : maechler 1189 function (x, i, j, value) {
683 :     if(!is.atomic(value))
684 : maechler 1615 stop(sprintf("RHS 'value' (class %s) matches 'ANY', but must match matrix class %s",
685 :     class(value),class(x)))
686 : maechler 1189 else stop("not-yet-implemented 'Matrix[<-' method")
687 :     })

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