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 2039 - (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 : maechler 1331 function(x) as.vector(as(x, "matrix")))
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 : maechler 1389
48 : maechler 1467 ## "base" has an isSymmetric() S3-generic since R 2.3.0
49 : maechler 1108 setMethod("isSymmetric", signature(object = "symmetricMatrix"),
50 : maechler 973 function(object,tol) TRUE)
51 : maechler 1108 setMethod("isSymmetric", signature(object = "triangularMatrix"),
52 : maechler 1174 ## TRUE iff diagonal:
53 :     function(object,tol) isDiagonal(object))
54 : maechler 1189
55 : maechler 1165 setMethod("isTriangular", signature(object = "triangularMatrix"),
56 : maechler 1238 function(object, ...) TRUE)
57 : maechler 1165
58 : maechler 1238 setMethod("isTriangular", signature(object = "matrix"), isTriMat)
59 :    
60 : maechler 1174 setMethod("isDiagonal", signature(object = "matrix"), .is.diagonal)
61 : maechler 886
62 : maechler 1174
63 :    
64 : maechler 579 setMethod("dim", signature(x = "Matrix"),
65 : maechler 698 function(x) x@Dim, valueClass = "integer")
66 : maechler 1705
67 : maechler 1738 setMethod("length", "Matrix", function(x) prod(dim(x)))
68 :    
69 : maechler 579 setMethod("dimnames", signature(x = "Matrix"), function(x) x@Dimnames)
70 : maechler 1705
71 :    
72 : maechler 607 ## not exported but used more than once for "dimnames<-" method :
73 :     ## -- or do only once for all "Matrix" classes ??
74 :     dimnamesGets <- function (x, value) {
75 :     d <- dim(x)
76 :     if (!is.list(value) || length(value) != 2 ||
77 : maechler 698 !(is.null(v1 <- value[[1]]) || length(v1) == d[1]) ||
78 :     !(is.null(v2 <- value[[2]]) || length(v2) == d[2]))
79 :     stop(sprintf("invalid dimnames given for '%s' object", class(x)))
80 : maechler 607 x@Dimnames <- list(if(!is.null(v1)) as.character(v1),
81 : maechler 698 if(!is.null(v2)) as.character(v2))
82 : maechler 607 x
83 :     }
84 :     setMethod("dimnames<-", signature(x = "Matrix", value = "list"),
85 : maechler 698 dimnamesGets)
86 : maechler 579
87 : maechler 658 setMethod("unname", signature("Matrix", force="missing"),
88 : maechler 698 function(obj) { obj@Dimnames <- list(NULL,NULL); obj})
89 : maechler 607
90 : maechler 1705 setMethod("all", signature(x = "Matrix"),
91 : maechler 2015 function(x, ..., na.rm)
92 :     callGeneric(as(x, "lMatrix"), ..., na.rm=na.rm))
93 :    
94 : maechler 1705 setMethod("any", signature(x = "Matrix"),
95 : maechler 2015 function(x, ..., na.rm)
96 :     callGeneric(as(x, "lMatrix"), ..., na.rm=na.rm))
97 : maechler 1705
98 : maechler 1832 ## NOTE: "&" and "|" are now in group "Logic" c "Ops" --> ./Ops.R
99 :     ## "!" is in ./not.R
100 : maechler 1705
101 :    
102 : bates 10 Matrix <-
103 : maechler 954 function (data = NA, nrow = 1, ncol = 1, byrow = FALSE, dimnames = NULL,
104 : maechler 1455 sparse = NULL, forceCheck = FALSE)
105 : bates 10 {
106 : maechler 1665 sparseDefault <- function(m) prod(dim(m)) > 2*sum(isN0(as(m, "matrix")))
107 : maechler 954
108 :     i.M <- is(data, "Matrix")
109 : maechler 1618
110 :     if(is.null(sparse1 <- sparse) && (i.M || is(data, "matrix")))
111 : maechler 1174 sparse <- sparseDefault(data)
112 : maechler 954
113 : maechler 1455 doDN <- TRUE
114 : maechler 1551 if (i.M) {
115 : maechler 1751 if(!missing(nrow) || !missing(ncol)|| !missing(byrow))
116 :     warning("'nrow', 'ncol', etc, are disregarded when 'data' is \"Matrix\" already")
117 : maechler 1174 sM <- is(data,"sparseMatrix")
118 : maechler 1551 if(!forceCheck && ((sparse && sM) || (!sparse && !sM)))
119 : maechler 1174 return(data)
120 :     ## else : convert dense <-> sparse -> at end
121 : maechler 954 }
122 :     else if (!is.matrix(data)) { ## cut & paste from "base::matrix" :
123 : maechler 698 if (missing(nrow))
124 :     nrow <- ceiling(length(data)/ncol)
125 :     else if (missing(ncol))
126 :     ncol <- ceiling(length(data)/nrow)
127 : maechler 1618 if(length(data) == 1 && is0(data) && !identical(sparse, FALSE)) {
128 :     ## Matrix(0, ...) : always sparse unless "sparse = FALSE":
129 :     if(is.null(sparse)) sparse1 <- sparse <- TRUE
130 : maechler 1825 i.M <- sM <- TRUE
131 : maechler 1315 ## will be sparse: do NOT construct full matrix!
132 :     data <- new(if(is.numeric(data)) "dgTMatrix" else
133 :     if(is.logical(data)) "lgTMatrix" else
134 :     stop("invalid 'data'"),
135 :     Dim = as.integer(c(nrow,ncol)),
136 : maechler 1332 Dimnames = if(is.null(dimnames)) list(NULL,NULL)
137 :     else dimnames)
138 : maechler 1315 } else { ## normal case
139 :     data <- .Internal(matrix(data, nrow, ncol, byrow))
140 :     if(is.null(sparse))
141 :     sparse <- sparseDefault(data)
142 :     dimnames(data) <- dimnames
143 :     }
144 : maechler 1455 doDN <- FALSE
145 : maechler 1751 } else if(!missing(nrow) || !missing(ncol)|| !missing(byrow))
146 : maechler 1747 warning("'nrow', 'ncol', etc, are disregarded for matrix 'data'")
147 :    
148 : maechler 1455 ## 'data' is now a "matrix" or "Matrix"
149 :     if (doDN && !is.null(dimnames))
150 : maechler 1189 dimnames(data) <- dimnames
151 : maechler 954
152 : maechler 1174 ## check for symmetric / triangular / diagonal :
153 :     isSym <- isSymmetric(data)
154 :     if((isTri <- !isSym))
155 :     isTri <- isTriangular(data)
156 :     isDiag <- isSym # cannot be diagonal if it isn't symmetric
157 :     if(isDiag)
158 :     isDiag <- isDiagonal(data)
159 :    
160 :     ## Find proper matrix class 'cl'
161 :     cl <-
162 : maechler 1618 if(isDiag && !isTRUE(sparse1))
163 : maechler 1174 "diagonalMatrix" # -> will automatically check for type
164 :     else {
165 :     ## consider it's type
166 :     ctype <-
167 :     if(is(data,"Matrix")) class(data)
168 :     else {
169 :     if("complex" == (ctype <- typeof(data)))
170 :     "z" else ctype
171 :     }
172 :     ctype <- substr(ctype, 1,1) # "d", "l", "i" or "z"
173 :     if(ctype == "z")
174 :     stop("complex matrices not yet implemented in Matrix package")
175 :     if(ctype == "i") {
176 :     warning("integer matrices not yet implemented in 'Matrix'; ",
177 :     "using 'double' ones'")
178 :     ctype <- "d"
179 :     }
180 :     paste(ctype,
181 :     if(sparse) {
182 :     if(isSym) "sCMatrix" else
183 :     if(isTri) "tCMatrix" else "gCMatrix"
184 :     } else { ## dense
185 :     if(isSym) "syMatrix" else
186 :     if(isTri) "trMatrix" else "geMatrix"
187 :     }, sep="")
188 :     }
189 :    
190 : maechler 1825 ## Can we coerce and be done?
191 :     if(!canCoerce(data,cl)) { ## try to coerce ``via'' virtual classes
192 :     if(sparse && !sM)
193 :     data <- as(data, "sparseMatrix")
194 :     else if(!sparse && !is(data, "denseMatrix"))
195 :     data <- as(data, "denseMatrix")
196 :     if(isTri && !is(data, "triangularMatrix"))
197 :     data <- as(data, "triangularMatrix")
198 :     else if(isSym && !is(data, "symmetricMatrix"))
199 :     data <- as(data, "symmetricMatrix")
200 :     }
201 :     ## now coerce in any case .. maybe producing sensible error message:
202 : maechler 1174 as(data, cl)
203 : bates 10 }
204 :    
205 : bates 683 ## Methods for operations where one argument is numeric
206 : maechler 512
207 : maechler 698 ## Using as.matrix() and rbind()
208 :     ## in order to get dimnames from names {at least potentially}:
209 :    
210 : bates 683 setMethod("%*%", signature(x = "Matrix", y = "numeric"),
211 : maechler 698 function(x, y) callGeneric(x, as.matrix(y)))
212 : bates 683 setMethod("%*%", signature(x = "numeric", y = "Matrix"),
213 : maechler 1660 function(x, y) callGeneric(matrix(x, nrow = 1, byrow=TRUE), y))
214 : bates 683
215 : maechler 2036 setMethod("%*%", signature(x = "Matrix", y = "matrix"),
216 :     function(x, y) callGeneric(x, Matrix(y)))
217 :     setMethod("%*%", signature(x = "matrix", y = "Matrix"),
218 :     function(x, y) callGeneric(Matrix(x), y))
219 :    
220 :    
221 : bates 683 setMethod("crossprod", signature(x = "Matrix", y = "numeric"),
222 : maechler 698 function(x, y = NULL) callGeneric(x, as.matrix(y)))
223 : bates 683 setMethod("crossprod", signature(x = "numeric", y = "Matrix"),
224 : maechler 1331 function(x, y = NULL) callGeneric(as.matrix(x), y))
225 : bates 683
226 : maechler 2036 setMethod("crossprod", signature(x = "Matrix", y = "matrix"),
227 : maechler 2039 function(x, y = NULL) callGeneric(x, Matrix(y)))
228 : maechler 2036 setMethod("crossprod", signature(x = "matrix", y = "Matrix"),
229 : maechler 2039 function(x, y = NULL) callGeneric(Matrix(x), y))
230 : maechler 2036
231 : maechler 1331 ## The as.matrix() promotion seems illogical to MM,
232 :     ## but is according to help(tcrossprod, package = "base") :
233 :     setMethod("tcrossprod", signature(x = "Matrix", y = "numeric"),
234 :     function(x, y = NULL) callGeneric(x, as.matrix(y)))
235 :     setMethod("tcrossprod", signature(x = "numeric", y = "Matrix"),
236 :     function(x, y = NULL) callGeneric(as.matrix(x), y))
237 : maechler 2036 setMethod("tcrossprod", signature(x = "Matrix", y = "matrix"),
238 : maechler 2039 function(x, y = NULL) callGeneric(x, Matrix(y)))
239 : maechler 2036 setMethod("tcrossprod", signature(x = "matrix", y = "Matrix"),
240 : maechler 2039 function(x, y = NULL) callGeneric(Matrix(x), y))
241 : maechler 1331
242 : maechler 1665 ## maybe not optimal
243 :     setMethod("solve", signature(a = "Matrix", b = "missing"),
244 :     function(a, b, ...) solve(a, Diagonal(nrow(a))))
245 :    
246 : bates 683 setMethod("solve", signature(a = "Matrix", b = "numeric"),
247 : maechler 2036 function(a, b, ...) callGeneric(a, Matrix(b)))
248 :     setMethod("solve", signature(a = "Matrix", b = "matrix"),
249 :     function(a, b, ...) callGeneric(a, Matrix(b)))
250 :     setMethod("solve", signature(a = "matrix", b = "Matrix"),
251 :     function(a, b, ...) callGeneric(Matrix(a), b))
252 :    
253 : maechler 1659 ## when no sub-class method is found, bail out
254 : maechler 1747 setMethod("solve", signature(a = "Matrix", b = "Matrix"),
255 :     function(a, b, ...) .bail.out.2("solve", class(a), class(b)))
256 : maechler 848
257 : maechler 925 ## bail-out methods in order to get better error messages
258 :     setMethod("%*%", signature(x = "Matrix", y = "Matrix"),
259 :     function (x, y)
260 :     stop(gettextf('not-yet-implemented method for <%s> %%*%% <%s>',
261 :     class(x), class(y))))
262 : maechler 946
263 : maechler 925 setMethod("crossprod", signature(x = "Matrix", y = "ANY"),
264 : maechler 946 function (x, y = NULL) .bail.out.2(.Generic, class(x), class(y)))
265 : maechler 956 setMethod("crossprod", signature(x = "ANY", y = "Matrix"),
266 :     function (x, y = NULL) .bail.out.2(.Generic, class(x), class(y)))
267 : maechler 1331 setMethod("tcrossprod", signature(x = "Matrix", y = "ANY"),
268 :     function (x, y = NULL) .bail.out.2(.Generic, class(x), class(y)))
269 :     setMethod("tcrossprod", signature(x = "ANY", y = "Matrix"),
270 :     function (x, y = NULL) .bail.out.2(.Generic, class(x), class(y)))
271 : maechler 925
272 : maechler 1331 ## cheap fallbacks
273 :     setMethod("crossprod", signature(x = "Matrix", y = "Matrix"),
274 :     function(x, y = NULL) t(x) %*% y)
275 :     setMethod("tcrossprod", signature(x = "Matrix", y = "Matrix"),
276 :     function(x, y = NULL) x %*% t(y))
277 :    
278 : maechler 956 ## There are special sparse methods; this is a "fall back":
279 :     setMethod("kronecker", signature(X = "Matrix", Y = "ANY",
280 : maechler 1805 FUN = "ANY", make.dimnames = "ANY"),
281 :     function(X, Y, FUN, make.dimnames, ...) {
282 : maechler 1825 if(is(X, "sparseMatrix"))
283 :     warning("using slow kronecker() method")
284 : maechler 1805 X <- as(X, "matrix") ; Matrix(callGeneric()) })
285 :    
286 : maechler 956 setMethod("kronecker", signature(X = "ANY", Y = "Matrix",
287 : maechler 1805 FUN = "ANY", make.dimnames = "ANY"),
288 :     function(X, Y, FUN, make.dimnames, ...) {
289 : maechler 1825 if(is(Y, "sparseMatrix"))
290 :     warning("using slow kronecker() method")
291 : maechler 1805 Y <- as(Y, "matrix") ; Matrix(callGeneric()) })
292 : maechler 956
293 :    
294 : maechler 1654 ## FIXME: All of these should never be called
295 :     setMethod("chol", signature(x = "Matrix"),
296 :     function(x, pivot = FALSE) .bail.out.1(.Generic, class(x)))
297 :     setMethod("determinant", signature(x = "Matrix"),
298 :     function(x, logarithm = TRUE) .bail.out.1(.Generic, class(x)))
299 :    
300 : maechler 1315 setMethod("diag", signature(x = "Matrix"),
301 :     function(x, nrow, ncol) .bail.out.1(.Generic, class(x)))
302 : maechler 946 setMethod("t", signature(x = "Matrix"),
303 :     function(x) .bail.out.1(.Generic, class(x)))
304 : maechler 925
305 : maechler 2005 setMethod("norm", signature(x = "Matrix", type = "character"),
306 :     function(x, type, ...) .bail.out.1(.Generic, class(x)))
307 :     setMethod("rcond", signature(x = "Matrix", type = "character"),
308 :     function(x, type, ...) .bail.out.1(.Generic, class(x)))
309 :    
310 :    
311 :     ## for all :
312 :     setMethod("norm", signature(x = "ANY", type = "missing"),
313 :     function(x, type, ...) norm(x, type = "O", ...))
314 :     setMethod("rcond", signature(x = "ANY", type = "missing"),
315 :     function(x, type, ...) rcond(x, type = "O", ...))
316 :    
317 :    
318 :    
319 :    
320 :    
321 : maechler 1799 ## MM: More or less "Cut & paste" from
322 :     ## --- diff.default() from R/src/library/base/R/diff.R :
323 :     setMethod("diff", signature(x = "Matrix"),
324 :     function(x, lag = 1, differences = 1, ...) {
325 :     if (length(lag) > 1 || length(differences) > 1 ||
326 :     lag < 1 || differences < 1)
327 :     stop("'lag' and 'differences' must be integers >= 1")
328 :     xlen <- nrow(x)
329 :     if (lag * differences >= xlen)
330 :     return(x[,FALSE][0]) # empty of proper mode
331 :    
332 :     i1 <- -1:-lag
333 :     for (i in 1:differences)
334 :     x <- x[i1, , drop = FALSE] -
335 :     x[-nrow(x):-(nrow(x)-lag+1), , drop = FALSE]
336 :     x
337 :     })
338 :    
339 : maechler 1829 setMethod("image", "Matrix",
340 :     function(x, ...) { # coercing to sparse is not inefficient,
341 :     ## since we need 'i' and 'j' for levelplot()
342 :     x <- as(as(x, "sparseMatrix"), "dMatrix")
343 :     callGeneric()
344 :     })
345 : maechler 1799
346 : maechler 1829
347 : maechler 956 ## Group Methods
348 :    
349 : maechler 1714 ##-> see ./Ops.R
350 : maechler 2005 ## ~~~~~
351 :     ## For all non-dMatrix objects, and note that "all" and "any" have their own
352 :     setMethod("Summary", signature(x = "Matrix", na.rm = "ANY"),
353 :     function(x, ..., na.rm)
354 :     callGeneric(as(x,"dMatrix"), ..., na.rm = na.rm))
355 : maechler 1655
356 : maechler 2005
357 : maechler 871 ### --------------------------------------------------------------------------
358 :     ###
359 :     ### Subsetting "[" and
360 :     ### SubAssign "[<-" : The "missing" cases can be dealt with here, "at the top":
361 : maechler 868
362 : maechler 886 ## Using "index" for indices should allow
363 : maechler 875 ## integer (numeric), logical, or character (names!) indices :
364 :    
365 : maechler 868 ## "x[]":
366 :     setMethod("[", signature(x = "Matrix",
367 :     i = "missing", j = "missing", drop = "ANY"),
368 :     function (x, i, j, drop) x)
369 : maechler 1225
370 : maechler 868 ## missing 'drop' --> 'drop = TRUE'
371 :     ## -----------
372 :     ## select rows
373 : maechler 886 setMethod("[", signature(x = "Matrix", i = "index", j = "missing",
374 : maechler 868 drop = "missing"),
375 : maechler 1799 function(x,i,j, drop) {
376 :     if(nargs() == 1) { ## e.g. M[0] , M[TRUE], M[1:2]
377 :     if(any(i)) as.vector(x)[i] else as.vector(x[1,1])[FALSE]
378 :     } else callGeneric(x, i=i, drop= TRUE)})
379 :    
380 : maechler 868 ## select columns
381 : maechler 886 setMethod("[", signature(x = "Matrix", i = "missing", j = "index",
382 : maechler 868 drop = "missing"),
383 :     function(x,i,j, drop) callGeneric(x, j=j, drop= TRUE))
384 : maechler 886 setMethod("[", signature(x = "Matrix", i = "index", j = "index",
385 : maechler 868 drop = "missing"),
386 :     function(x,i,j, drop) callGeneric(x, i=i, j=j, drop= TRUE))
387 :    
388 : maechler 875 ## bail out if any of (i,j,drop) is "non-sense"
389 :     setMethod("[", signature(x = "Matrix", i = "ANY", j = "ANY", drop = "ANY"),
390 :     function(x,i,j, drop)
391 :     stop("invalid or not-yet-implemented 'Matrix' subsetting"))
392 :    
393 : maechler 1472 ## logical indexing, such as M[ M >= 7 ] *BUT* also M[ M[,1] >= 3,],
394 :     ## The following is *both* for M [ <logical> ]
395 :     ## and also for M [ <logical> , ]
396 :     .M.sub.i.logical <- function (x, i, j, drop)
397 :     {
398 :     nA <- nargs()
399 :     if(nA == 2) { ## M [ M >= 7 ]
400 : maechler 1673 ## FIXME: when both 'x' and 'i' are sparse, this can be very inefficient
401 : maechler 1472 as(x, geClass(x))@x[as.vector(i)]
402 :     ## -> error when lengths don't match
403 :     } else if(nA == 3) { ## M [ M[,1, drop=FALSE] >= 7, ]
404 :     stop("not-yet-implemented 'Matrix' subsetting") ## FIXME
405 :    
406 :     } else stop("nargs() = ", nA,
407 : maechler 1747 ". Extraneous illegal arguments inside '[ .. ]' ?")
408 : maechler 1472 }
409 : maechler 1225 setMethod("[", signature(x = "Matrix", i = "lMatrix", j = "missing",
410 :     drop = "ANY"),
411 : maechler 1472 .M.sub.i.logical)
412 : maechler 1225 setMethod("[", signature(x = "Matrix", i = "logical", j = "missing",
413 :     drop = "ANY"),
414 : maechler 1472 .M.sub.i.logical)
415 : maechler 1225
416 :    
417 : maechler 1673 ## A[ ij ] where ij is (i,j) 2-column matrix :
418 :     .M.sub.i.2col <- function (x, i, j, drop)
419 :     {
420 :     nA <- nargs()
421 :     if(nA == 2) { ## M [ cbind(ii,jj) ]
422 :     if(!is.integer(nc <- ncol(i)))
423 :     stop("'i' has no integer column number",
424 :     " should never happen; please report")
425 :     if(is.logical(i))
426 :     return(.M.sub.i.logical(x,i,j,drop))
427 :     else if(!is.numeric(i) || nc != 2)
428 :     stop("such indexing must be by logical or 2-column numeric matrix")
429 :     m <- nrow(i)
430 :     if(m == 0) return(vector(mode = .type.kind[.M.kind(x)]))
431 :     ## else
432 :     i1 <- i[,1]
433 :     i2 <- i[,2]
434 :     ## potentially inefficient -- FIXME --
435 :     unlist(lapply(seq_len(m), function(j) x[i1[j], i2[j]]))
436 : maechler 868
437 : maechler 1747 } else stop("nargs() = ", nA,
438 :     ". Extraneous illegal arguments inside '[ .. ]' ?")
439 : maechler 1673 }
440 :     setMethod("[", signature(x = "Matrix", i = "matrix", j = "missing"),# drop="ANY"
441 :     .M.sub.i.2col)
442 : maechler 868
443 : maechler 1472
444 : maechler 871 ### "[<-" : -----------------
445 : maechler 868
446 : maechler 871 ## x[] <- value :
447 :     setReplaceMethod("[", signature(x = "Matrix", i = "missing", j = "missing",
448 : maechler 1189 value = "ANY"),## double/logical/...
449 :     function (x, value) {
450 : maechler 1615 ## Fails for 'nMatrix' ... FIXME : make sure have method there
451 : maechler 1747 x@x <- rep(value, length = length(x@x))
452 : maechler 1615 validObject(x)# check if type and lengths above match
453 :     x
454 : maechler 1189 })
455 : maechler 871
456 : maechler 1673 ## A[ ij ] <- value, where ij is (i,j) 2-column matrix :
457 : maechler 1724 ## ---------------- The cheap general method --- FIXME: provide special ones
458 : maechler 1673 .M.repl.i.2col <- function (x, i, j, value)
459 :     {
460 :     nA <- nargs()
461 :     if(nA == 3) { ## M [ cbind(ii,jj) ] <- value
462 :     if(!is.integer(nc <- ncol(i)))
463 :     stop("'i' has no integer column number",
464 :     " should never happen; please report")
465 : maechler 1724 else if(!is.numeric(i) || nc != 2)
466 :     stop("such indexing must be by logical or 2-column numeric matrix")
467 : maechler 1673 if(is.logical(i)) {
468 : maechler 1738 message(".M.repl.i.2col(): drop 'matrix' case ...")
469 : maechler 1673 i <- c(i) # drop "matrix"
470 :     return( callNextMethod() )
471 : maechler 1724 }
472 :     if(!is.integer(i)) storage.mode(i) <- "integer"
473 :     if(any(i < 0))
474 :     stop("negative values are not allowed in a matrix subscript")
475 :     if(any(is.na(i)))
476 :     stop("NAs are not allowed in subscripted assignments")
477 :     if(any(i0 <- (i == 0))) # remove them
478 :     i <- i[ - which(i0, arr.ind = TRUE)[,"row"], ]
479 :     ## now have integer i >= 1
480 : maechler 1673 m <- nrow(i)
481 : maechler 1724 ## mod.x <- .type.kind[.M.kind(x)]
482 : maechler 1673 if(length(value) > 0 && m %% length(value) != 0)
483 :     warning("number of items to replace is not a multiple of replacement length")
484 :     ## recycle:
485 :     value <- rep(value, length = m)
486 :     i1 <- i[,1]
487 :     i2 <- i[,2]
488 :     ## inefficient -- FIXME -- (also loses "symmetry" unnecessarily)
489 :     for(k in seq_len(m))
490 :     x[i1[k], i2[k]] <- value[k]
491 : maechler 1724
492 : maechler 1673 x
493 : maechler 1747 } else stop("nargs() = ", nA,
494 :     ". Extraneous illegal arguments inside '[ .. ]' ?")
495 : maechler 1673 }
496 : maechler 1724
497 : maechler 1673 setReplaceMethod("[", signature(x = "Matrix", i = "matrix", j = "missing",
498 :     value = "replValue"),
499 :     .M.repl.i.2col)
500 :    
501 :    
502 : maechler 1615 setReplaceMethod("[", signature(x = "Matrix", i = "ANY", j = "ANY",
503 :     value = "Matrix"),
504 : maechler 1705 function (x, i, j, value) {
505 : maechler 1724 ### *TEMPORARY* diagnostic output:
506 :     ## cat("<Matrix1>[i,j] <- <Matrix1>:\n<Matrix1> = x :")
507 :     ## str(x)
508 :     ## cat("<Matrix2> = value :")
509 :     ## str(value)
510 :     ## cat("i :"); if(!missing(i)) str(i) else cat("<missing>\n")
511 :     ## cat("j :"); if(!missing(j)) str(j) else cat("<missing>\n")
512 : maechler 1705
513 :     callGeneric(x=x, i=i, j=j, value = as.vector(value))
514 :     })
515 :     setReplaceMethod("[", signature(x = "Matrix", i = "ANY", j = "ANY",
516 :     value = "Matrix"),
517 : maechler 1615 function (x, i, j, value)
518 :     callGeneric(x=x, i=i, j=j, value = as.vector(value)))
519 : maechler 1705
520 : maechler 1615 setReplaceMethod("[", signature(x = "Matrix", i = "ANY", j = "ANY",
521 :     value = "matrix"),
522 :     function (x, i, j, value)
523 :     callGeneric(x=x, i=i, j=j, value = c(value)))
524 :    
525 : maechler 1189 ## (ANY,ANY,ANY) is used when no `real method' is implemented :
526 : maechler 871 setReplaceMethod("[", signature(x = "Matrix", i = "ANY", j = "ANY",
527 :     value = "ANY"),
528 : maechler 1189 function (x, i, j, value) {
529 :     if(!is.atomic(value))
530 : maechler 1615 stop(sprintf("RHS 'value' (class %s) matches 'ANY', but must match matrix class %s",
531 :     class(value),class(x)))
532 : maechler 1189 else stop("not-yet-implemented 'Matrix[<-' method")
533 :     })

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