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 1326 - (view) (download)

1 : maechler 607 #### Toplevel ``virtual'' class "Matrix"
2 :    
3 : maechler 956 ## ## probably not needed eventually:
4 :     ## setAs(from = "ddenseMatrix", to = "matrix",
5 :     ## function(from) {
6 :     ## if(length(d <- dim(from)) != 2) stop("dim(.) has not length 2")
7 :     ## array(from@x, dim = d, dimnames = dimnames(from))
8 :     ## })
9 : maechler 607
10 : maechler 676 ## should propagate to all subclasses:
11 : maechler 658 setMethod("as.matrix", signature(x = "Matrix"), function(x) as(x, "matrix"))
12 : maechler 956 ## for 'Matrix' objects, as.array() should be equivalent:
13 :     setMethod("as.array", signature(x = "Matrix"), function(x) as(x, "matrix"))
14 : bates 1326 ## head and tail apply to all Matrix objects for which subscripting is allowed
15 :     setMethod("head", signature(x = "Matrix"),
16 :     function(x, n = 6, ...)
17 :     x[seq(len = min(n, nrow(x))), , drop = FALSE])
18 :     setMethod("tail", signature(x = "Matrix"),
19 :     function (x, n = 6, addrownums = TRUE, ...)
20 :     {
21 :     nrx <- nrow(x)
22 :     sel <- seq(to = nrx, length = min(n, nrx))
23 :     ans <- x[sel, , drop = FALSE]
24 :     if (addrownums && is.null(rownames(x)))
25 :     rownames(ans) <- paste("[", sel, ",]", sep = "")
26 :     ans
27 :     })
28 : maechler 658
29 : maechler 956 ## slow "fall back" method {subclasses should have faster ones}:
30 :     setMethod("as.vector", signature(x = "Matrix", mode = "missing"),
31 :     function(x) as.vector(as(x, "matrix")))
32 :    
33 :    
34 : maechler 1174 ## Note that isSymmetric is *not* exported
35 :     ## but that "base" has an isSymmetric() S3-generic since R 2.3.0
36 : maechler 1108 setMethod("isSymmetric", signature(object = "symmetricMatrix"),
37 : maechler 973 function(object,tol) TRUE)
38 : maechler 1108 setMethod("isSymmetric", signature(object = "triangularMatrix"),
39 : maechler 1174 ## TRUE iff diagonal:
40 :     function(object,tol) isDiagonal(object))
41 : maechler 1189
42 : maechler 1174 if(paste(R.version$major, R.version$minor, sep=".") < "2.3")
43 :     ## need a "matrix" method as in R 2.3 and later
44 :     setMethod("isSymmetric", signature(object = "matrix"),
45 : maechler 1189 function(object, tol = 100*.Machine$double.eps, ...)
46 :     {
47 :     ## pretest: is it square?
48 :     d <- dim(object)
49 :     if(d[1] != d[2]) return(FALSE)
50 :     ## for `broken' all.equal in R <= 2.2.x:
51 :     dn <- dimnames(object)
52 :     if(!identical(dn[1], dn[2])) return(FALSE)
53 :     test <-
54 :     if(is.complex(object))
55 :     all.equal.numeric(object, Conj(t(object)), tol = tol, ...)
56 :     else # numeric, character, ..
57 :     all.equal(object, t(object), tol = tol, ...)
58 :     isTRUE(test)
59 :     })
60 : maechler 973
61 : maechler 1174
62 : maechler 1165 setMethod("isTriangular", signature(object = "triangularMatrix"),
63 : maechler 1238 function(object, ...) TRUE)
64 : maechler 1165
65 : maechler 1238 setMethod("isTriangular", signature(object = "matrix"), isTriMat)
66 :    
67 : maechler 1174 setMethod("isDiagonal", signature(object = "matrix"), .is.diagonal)
68 : maechler 886
69 : maechler 1174
70 :    
71 : maechler 579 setMethod("dim", signature(x = "Matrix"),
72 : maechler 698 function(x) x@Dim, valueClass = "integer")
73 : maechler 579 setMethod("dimnames", signature(x = "Matrix"), function(x) x@Dimnames)
74 : maechler 607 ## not exported but used more than once for "dimnames<-" method :
75 :     ## -- or do only once for all "Matrix" classes ??
76 :     dimnamesGets <- function (x, value) {
77 :     d <- dim(x)
78 :     if (!is.list(value) || length(value) != 2 ||
79 : maechler 698 !(is.null(v1 <- value[[1]]) || length(v1) == d[1]) ||
80 :     !(is.null(v2 <- value[[2]]) || length(v2) == d[2]))
81 :     stop(sprintf("invalid dimnames given for '%s' object", class(x)))
82 : maechler 607 x@Dimnames <- list(if(!is.null(v1)) as.character(v1),
83 : maechler 698 if(!is.null(v2)) as.character(v2))
84 : maechler 607 x
85 :     }
86 :     setMethod("dimnames<-", signature(x = "Matrix", value = "list"),
87 : maechler 698 dimnamesGets)
88 : maechler 579
89 : maechler 658 setMethod("unname", signature("Matrix", force="missing"),
90 : maechler 698 function(obj) { obj@Dimnames <- list(NULL,NULL); obj})
91 : maechler 607
92 : bates 10 Matrix <-
93 : maechler 954 function (data = NA, nrow = 1, ncol = 1, byrow = FALSE, dimnames = NULL,
94 : maechler 1174 sparse = NULL)
95 : bates 10 {
96 : maechler 954 sparseDefault <- function(m)
97 : maechler 1174 prod(dim(m)) > 2*sum(as(m, "matrix") != 0)
98 : maechler 954
99 :     i.M <- is(data, "Matrix")
100 :     if(is.null(sparse) && (i.M || is(data, "matrix")))
101 : maechler 1174 sparse <- sparseDefault(data)
102 : maechler 954
103 :     if (i.M) {
104 : maechler 1174 sM <- is(data,"sparseMatrix")
105 :     if((sparse && sM) || (!sparse && !sM))
106 :     return(data)
107 :     ## else : convert dense <-> sparse -> at end
108 : maechler 954 }
109 :     else if (!is.matrix(data)) { ## cut & paste from "base::matrix" :
110 : maechler 698 if (missing(nrow))
111 :     nrow <- ceiling(length(data)/ncol)
112 :     else if (missing(ncol))
113 :     ncol <- ceiling(length(data)/nrow)
114 : maechler 1315 if(length(data) == 1 && data == 0 && !identical(sparse,FALSE)) {
115 :     if(is.null(sparse)) sparse <- TRUE
116 :     ## will be sparse: do NOT construct full matrix!
117 :     data <- new(if(is.numeric(data)) "dgTMatrix" else
118 :     if(is.logical(data)) "lgTMatrix" else
119 :     stop("invalid 'data'"),
120 :     Dim = as.integer(c(nrow,ncol)),
121 :     Dimnames = if(is.null(dimnames))
122 :     list(NULL,NULL) else dimnames)
123 :     } else { ## normal case
124 :     data <- .Internal(matrix(data, nrow, ncol, byrow))
125 :     if(is.null(sparse))
126 :     sparse <- sparseDefault(data)
127 :     dimnames(data) <- dimnames
128 :     }
129 : maechler 1189 } else if (!is.null(dimnames))
130 :     dimnames(data) <- dimnames
131 : maechler 954
132 :     ## 'data' is now a "matrix" or "Matrix"
133 : maechler 1174
134 :     ## check for symmetric / triangular / diagonal :
135 :     isSym <- isSymmetric(data)
136 :     if((isTri <- !isSym))
137 :     isTri <- isTriangular(data)
138 :     isDiag <- isSym # cannot be diagonal if it isn't symmetric
139 :     if(isDiag)
140 :     isDiag <- isDiagonal(data)
141 :    
142 : maechler 965 ### TODO: Compare with as.Matrix() and its tests in ./dgeMatrix.R
143 : maechler 1174
144 :     ## Find proper matrix class 'cl'
145 :     cl <-
146 :     if(isDiag)
147 :     "diagonalMatrix" # -> will automatically check for type
148 :     else {
149 :     ## consider it's type
150 :     ctype <-
151 :     if(is(data,"Matrix")) class(data)
152 :     else {
153 :     if("complex" == (ctype <- typeof(data)))
154 :     "z" else ctype
155 :     }
156 :     ctype <- substr(ctype, 1,1) # "d", "l", "i" or "z"
157 :     if(ctype == "z")
158 :     stop("complex matrices not yet implemented in Matrix package")
159 :     if(ctype == "i") {
160 :     warning("integer matrices not yet implemented in 'Matrix'; ",
161 :     "using 'double' ones'")
162 :     ctype <- "d"
163 :     }
164 :     paste(ctype,
165 :     if(sparse) {
166 :     if(isSym) "sCMatrix" else
167 :     if(isTri) "tCMatrix" else "gCMatrix"
168 :     } else { ## dense
169 :     if(isSym) "syMatrix" else
170 :     if(isTri) "trMatrix" else "geMatrix"
171 :     }, sep="")
172 :     }
173 :    
174 :     ## Now coerce and return
175 :     as(data, cl)
176 : bates 10 }
177 :    
178 : bates 683 ## Methods for operations where one argument is numeric
179 : maechler 512
180 : maechler 698 ## Using as.matrix() and rbind()
181 :     ## in order to get dimnames from names {at least potentially}:
182 :    
183 : bates 683 setMethod("%*%", signature(x = "Matrix", y = "numeric"),
184 : maechler 698 function(x, y) callGeneric(x, as.matrix(y)))
185 : bates 683
186 :     setMethod("%*%", signature(x = "numeric", y = "Matrix"),
187 : maechler 698 function(x, y) callGeneric(rbind(x), y))
188 : bates 683
189 :     setMethod("crossprod", signature(x = "Matrix", y = "numeric"),
190 : maechler 698 function(x, y = NULL) callGeneric(x, as.matrix(y)))
191 : bates 683
192 :     setMethod("crossprod", signature(x = "numeric", y = "Matrix"),
193 : maechler 698 function(x, y = NULL) callGeneric(rbind(x), y))
194 : bates 683
195 :     setMethod("solve", signature(a = "Matrix", b = "numeric"),
196 : maechler 698 function(a, b, ...) callGeneric(a, as.matrix(b)))
197 : maechler 848
198 : maechler 925 ## bail-out methods in order to get better error messages
199 :     setMethod("%*%", signature(x = "Matrix", y = "Matrix"),
200 :     function (x, y)
201 :     stop(gettextf('not-yet-implemented method for <%s> %%*%% <%s>',
202 :     class(x), class(y))))
203 : maechler 946
204 : maechler 925 setMethod("crossprod", signature(x = "Matrix", y = "ANY"),
205 : maechler 946 function (x, y = NULL) .bail.out.2(.Generic, class(x), class(y)))
206 : maechler 956 setMethod("crossprod", signature(x = "ANY", y = "Matrix"),
207 :     function (x, y = NULL) .bail.out.2(.Generic, class(x), class(y)))
208 : maechler 925
209 : maechler 956 ## There are special sparse methods; this is a "fall back":
210 :     setMethod("kronecker", signature(X = "Matrix", Y = "ANY",
211 :     FUN = "ANY", make.dimnames = "ANY"),
212 :     function(X, Y, FUN, make.dimnames, ...) {
213 :     X <- as(X, "matrix") ; Matrix(callGeneric()) })
214 :     setMethod("kronecker", signature(X = "ANY", Y = "Matrix",
215 :     FUN = "ANY", make.dimnames = "ANY"),
216 :     function(X, Y, FUN, make.dimnames, ...) {
217 :     Y <- as(Y, "matrix") ; Matrix(callGeneric()) })
218 :    
219 :    
220 : maechler 1315 setMethod("diag", signature(x = "Matrix"),
221 :     function(x, nrow, ncol) .bail.out.1(.Generic, class(x)))
222 : maechler 946 setMethod("t", signature(x = "Matrix"),
223 :     function(x) .bail.out.1(.Generic, class(x)))
224 : maechler 925
225 : maechler 956 ## Group Methods
226 :     setMethod("+", signature(e1 = "Matrix", e2 = "missing"), function(e1) e1)
227 :     ## "fallback":
228 :     setMethod("-", signature(e1 = "Matrix", e2 = "missing"),
229 :     function(e1) {
230 :     warning("inefficient method used for \"- e1\"")
231 :     0-e1
232 :     })
233 :    
234 :     ## bail-outs:
235 : maechler 946 setMethod("Compare", signature(e1 = "Matrix", e2 = "Matrix"),
236 : maechler 954 function(e1, e2) {
237 :     d <- dimCheck(e1,e2)
238 :     .bail.out.2(.Generic, class(e1), class(e2))
239 :     })
240 : maechler 946 setMethod("Compare", signature(e1 = "Matrix", e2 = "ANY"),
241 :     function(e1, e2) .bail.out.2(.Generic, class(e1), class(e2)))
242 :     setMethod("Compare", signature(e1 = "ANY", e2 = "Matrix"),
243 :     function(e1, e2) .bail.out.2(.Generic, class(e1), class(e2)))
244 :    
245 :    
246 :    
247 : maechler 871 ### --------------------------------------------------------------------------
248 :     ###
249 :     ### Subsetting "[" and
250 :     ### SubAssign "[<-" : The "missing" cases can be dealt with here, "at the top":
251 : maechler 868
252 : maechler 886 ## Using "index" for indices should allow
253 : maechler 875 ## integer (numeric), logical, or character (names!) indices :
254 :    
255 : maechler 868 ## "x[]":
256 :     setMethod("[", signature(x = "Matrix",
257 :     i = "missing", j = "missing", drop = "ANY"),
258 :     function (x, i, j, drop) x)
259 : maechler 1225
260 : maechler 868 ## missing 'drop' --> 'drop = TRUE'
261 :     ## -----------
262 :     ## select rows
263 : maechler 886 setMethod("[", signature(x = "Matrix", i = "index", j = "missing",
264 : maechler 868 drop = "missing"),
265 :     function(x,i,j, drop) callGeneric(x, i=i, drop= TRUE))
266 :     ## select columns
267 : maechler 886 setMethod("[", signature(x = "Matrix", i = "missing", j = "index",
268 : maechler 868 drop = "missing"),
269 :     function(x,i,j, drop) callGeneric(x, j=j, drop= TRUE))
270 : maechler 886 setMethod("[", signature(x = "Matrix", i = "index", j = "index",
271 : maechler 868 drop = "missing"),
272 :     function(x,i,j, drop) callGeneric(x, i=i, j=j, drop= TRUE))
273 :    
274 : maechler 875 ## bail out if any of (i,j,drop) is "non-sense"
275 :     setMethod("[", signature(x = "Matrix", i = "ANY", j = "ANY", drop = "ANY"),
276 :     function(x,i,j, drop)
277 :     stop("invalid or not-yet-implemented 'Matrix' subsetting"))
278 :    
279 : maechler 1225 ## "logical *vector* indexing, such as M [ M >= 10 ] :
280 :     setMethod("[", signature(x = "Matrix", i = "lMatrix", j = "missing",
281 :     drop = "ANY"),
282 :     function (x, i, j, drop) {
283 :     as(x, geClass(x))@x[as.vector(i)]
284 :     # -> error when lengths don't match
285 :     })
286 :    
287 :     setMethod("[", signature(x = "Matrix", i = "logical", j = "missing",
288 :     drop = "ANY"),
289 :     function (x, i, j, drop) as(x, geClass(x))@x[i])
290 :    
291 :    
292 : maechler 868 ## "FIXME:"
293 :     ## How can we get at A[ ij ] where ij is (i,j) 2-column matrix?
294 :     ## and A[ LL ] where LL is a logical *vector*
295 : maechler 886 ## -> [.data.frame uses nargs() - can we do this in the *generic* ?
296 : maechler 868
297 :    
298 : maechler 871 ### "[<-" : -----------------
299 : maechler 868
300 : maechler 871 ## x[] <- value :
301 :     setReplaceMethod("[", signature(x = "Matrix", i = "missing", j = "missing",
302 : maechler 1189 value = "ANY"),## double/logical/...
303 :     function (x, value) {
304 :     x@x <- value
305 :     validObject(x)# check if type and lengths above match
306 :     x
307 :     })
308 : maechler 871
309 : maechler 1189 ## Method for all 'Matrix' kinds (rather than incomprehensible error messages);
310 :     ## (ANY,ANY,ANY) is used when no `real method' is implemented :
311 : maechler 871 setReplaceMethod("[", signature(x = "Matrix", i = "ANY", j = "ANY",
312 :     value = "ANY"),
313 : maechler 1189 function (x, i, j, value) {
314 :     if(!is.atomic(value))
315 :     stop("RHS 'value' must match matrix class ", class(x))
316 :     else stop("not-yet-implemented 'Matrix[<-' method")
317 :     })
318 : maechler 871
319 :    
320 : maechler 1290 ## The trivial methods :
321 :     setMethod("cbind2", signature(x = "Matrix", y = "NULL"),
322 :     function(x, y) x)
323 :     setMethod("cbind2", signature(x = "Matrix", y = "missing"),
324 :     function(x, y) x)
325 :     setMethod("cbind2", signature(x = "NULL", y="Matrix"),
326 :     function(x, y) x)
327 : maechler 871
328 : maechler 1290 setMethod("rbind2", signature(x = "Matrix", y = "NULL"),
329 :     function(x, y) x)
330 :     setMethod("rbind2", signature(x = "Matrix", y = "missing"),
331 :     function(x, y) x)
332 :     setMethod("rbind2", signature(x = "NULL", y="Matrix"),
333 :     function(x, y) x)
334 : maechler 875
335 : maechler 1290 ## Makes sure one gets x decent error message for the unimplemented cases:
336 :     setMethod("cbind2", signature(x = "Matrix", y = "Matrix"),
337 :     function(x, y) {
338 :     rowCheck(x,y)
339 :     stop(gettextf("cbind2() method for (%s,%s) not-yet defined",
340 :     class(x), class(y)))
341 :     })
342 : maechler 908
343 : maechler 1290 ## Use a working fall back {particularly useful for sparse}:
344 :     ## FIXME: implement rbind2 via "cholmod" for C* and Tsparse ones
345 :     setMethod("rbind2", signature(x = "Matrix", y = "Matrix"),
346 :     function(x, y) {
347 :     colCheck(x,y)
348 :     t(cbind2(t(x), t(y)))
349 :     })

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