# SCM Repository

[matrix] Annotation of /pkg/tests/indexing.R
 [matrix] / pkg / tests / indexing.R

# Annotation of /pkg/tests/indexing.R

 1 : maechler 687 #### For both 'Extract' ("[") and 'Replace' ("[<-") Method testing 2 : 3 : library(Matrix) 4 : 5 : maechler 907 source(system.file("test-tools.R", package = "Matrix"))# identical3() etc 6 : maechler 687 7 : maechler 873 ### Dense Matrices 8 : 9 : maechler 687 m <- Matrix(1:28, nrow = 7) 10 : maechler 873 validObject(m) ; m@x <- as.double(m@x) ; validObject(m) 11 : stopifnot(identical(m, m[]), 12 : identical(m[2, 3], 16), # simple number 13 : identical(m[2, 3:4], c(16,23))) # simple numeric of length 2 14 : maechler 687 15 : maechler 873 m[2, 3:4, drop=FALSE] # sub matrix of class 'dgeMatrix' 16 : m[-(4:7), 3:4] # dito; the upper right corner of 'm' 17 : maechler 687 18 : maechler 873 ## rows or columns only: 19 : m[1,] # first row, as simple numeric vector 20 : m[,2] # 2nd column 21 : m[,1:2] # sub matrix of first two columns 22 : m[-(1:6),, drop=FALSE] # not the first 6 rows, i.e. only the 7th 23 : maechler 687 24 : maechler 873 ## logical indexing 25 : stopifnot(identical(m[2,3], m[(1:nrow(m)) == 2, (1:ncol(m)) == 3]), 26 : identical(m[2,], m[(1:nrow(m)) == 2, ]), 27 : identical(m[,3:4], m[, (1:4) >= 3])) 28 : 29 : maechler 886 ## dimnames indexing: 30 : mn <- m 31 : dimnames(mn) <- list(paste("r",letters[1:nrow(mn)],sep=""), 32 : LETTERS[1:ncol(mn)]) 33 : mn["rd", "D"] 34 : stopifnot(identical(mn["rc", "D"], mn[3,4]), 35 : identical(mn[, "A"], mn[,1]), 36 : identical(mn[c("re", "rb"), "B"], mn[c(5,2), 2]) 37 : ) 38 : maechler 873 39 : maechler 886 mo <- m 40 : m[2,3] <- 100 41 : m[1:2, 4] <- 200 42 : m[, 1] <- -1 43 : m[1:3,] 44 : 45 : maechler 873 ## TODO: more --- particularly once we have "m > 10" working! 46 : 47 : 48 : maechler 687 ### Sparse Matrices 49 : 50 : m <- 1:800 51 : set.seed(101) ; m[sample(800, 600)] <- 0 52 : m <- Matrix(m, nrow = 40) 53 : mm <- as(m, "matrix") 54 : dimnames(mm) <- NULL ## << workaround: as(, "matrix") has NULL dimnames 55 : str(mC <- as(m, "dgCMatrix")) 56 : str(mT <- as(m, "dgTMatrix")) 57 : stopifnot(identical(mT, as(mC, "dgTMatrix")), 58 : identical(mC, as(mT, "dgCMatrix"))) 59 : 60 : mC[,1] 61 : mC[1:2,] 62 : mC[7, drop = FALSE] 63 : 64 : mT[,c(2,4)] 65 : mT[1,] 66 : mT[4, drop = FALSE] 67 : stopifnot(identical3(mm[,1], mC[,1], mT[,1]), 68 : identical3(mm[3,], mC[3,], mT[3,]), 69 : identical3(mT[2,3], mC[2,3], 0), 70 : identical(mT[], mT), 71 : ## TODO: identical4() with m[c(3,7), 2:4] 72 : identical3(as(mC[c(3,7), 2:4],"matrix"), mm[c(3,7), 2:4], 73 : as(mT[c(3,7), 2:4],"matrix"))) 74 : 75 : maechler 886 ## At least these now give a nicely understandable error: 76 : try(mT[1, 4] <- -99) 77 : try(mT[2:3, ] <- 0)