Methods for "[<-", i.e., extraction or subsetting mostly of matrices, in package Matrix.

Note: Contrary to standard matrix assignment in base R, in x[..] <- val it is typically an error (see stop) when the type or class of val would require the class of x to be changed, e.g., when x is logical, say "lsparseMatrix", and val is numeric. In other cases, e.g., when x is a "nsparseMatrix" and val is not TRUE or FALSE, a warning is signalled, and val is “interpreted” as logical, and (logical) NA is interpreted as TRUE.

Methods

There are many many more than these:

x = "Matrix", i = "missing", j = "missing", value= "ANY"

is currently a simple fallback method implementation which ensures “readable” error messages.

x = "Matrix", i = "ANY", j = "ANY", value= "ANY"

currently gives an error

x = "denseMatrix", i = "index", j = "missing", value= "numeric"

...

x = "denseMatrix", i = "index", j = "index", value= "numeric"

...

x = "denseMatrix", i = "missing", j = "index", value= "numeric"

...

See also

[-methods for subsetting "Matrix" objects; the index class; Extract about the standard subset assignment (and extraction).

Examples


set.seed(101)
(a <- m <- Matrix(round(rnorm(7*4),2), nrow = 7))
#> 7 x 4 Matrix of class "dgeMatrix"
#>       [,1]  [,2]  [,3]  [,4]
#> [1,] -0.33 -0.11 -0.24  0.71
#> [2,]  0.55  0.92 -0.19 -0.27
#> [3,] -0.67 -0.22 -0.85 -1.46
#> [4,]  0.21  0.53  0.06  0.74
#> [5,]  0.31 -0.79 -0.82 -1.41
#> [6,]  1.17  1.43 -2.05  0.47
#> [7,]  0.62 -1.47 -0.16 -0.12

a[] <- 2.2 # <<- replaces **every** entry
a
#> 7 x 4 Matrix of class "dgeMatrix"
#>      [,1] [,2] [,3] [,4]
#> [1,]  2.2  2.2  2.2  2.2
#> [2,]  2.2  2.2  2.2  2.2
#> [3,]  2.2  2.2  2.2  2.2
#> [4,]  2.2  2.2  2.2  2.2
#> [5,]  2.2  2.2  2.2  2.2
#> [6,]  2.2  2.2  2.2  2.2
#> [7,]  2.2  2.2  2.2  2.2
## as do these:
a[,] <- 3 ; a[TRUE,] <- 4

m[2, 3]  <- 3.14 # simple number
m[3, 3:4]<- 3:4  # simple numeric of length 2

## sub matrix assignment:
m[-(4:7), 3:4] <- cbind(1,2:4) #-> upper right corner of 'm'
m[3:5, 2:3] <- 0
m[6:7, 1:2] <- Diagonal(2)
m
#> 7 x 4 Matrix of class "dgeMatrix"
#>       [,1]  [,2]  [,3]  [,4]
#> [1,] -0.33 -0.11  1.00  2.00
#> [2,]  0.55  0.92  1.00  3.00
#> [3,] -0.67  0.00  0.00  4.00
#> [4,]  0.21  0.00  0.00  0.74
#> [5,]  0.31  0.00  0.00 -1.41
#> [6,]  1.00  0.00 -2.05  0.47
#> [7,]  0.00  1.00 -0.16 -0.12

## rows or columns only:
m[1,] <- 10
m[,2] <- 1:7
m[-(1:6), ] <- 3:0 # not the first 6 rows, i.e. only the 7th
as(m, "sparseMatrix")
#> 7 x 4 sparse Matrix of class "dgCMatrix"
#>                         
#> [1,] 10.00 1 10.00 10.00
#> [2,]  0.55 2  1.00  3.00
#> [3,] -0.67 3  .     4.00
#> [4,]  0.21 4  .     0.74
#> [5,]  0.31 5  .    -1.41
#> [6,]  1.00 6 -2.05  0.47
#> [7,]  3.00 2  1.00  .