User friendly construction of sparse vectors, i.e., objects inheriting from class sparseVector, from indices and values of its non-zero entries.

sparseVector(x, i, length)

Details

zero entries in x are dropped automatically, analogously as drop0() acts on sparse matrices.

Arguments

x

vector of the non zero entries; may be missing in which case a "nsparseVector" will be returned.

i

integer vector (of the same length as x) specifying the indices of the non-zero (or non-TRUE) entries of the sparse vector.

length

length of the sparse vector.

Value

a sparse vector, i.e., inheriting from class sparseVector.

Author

Martin Maechler

See also

sparseMatrix() constructor for sparse matrices; the class sparseVector.

Examples

str(sv <- sparseVector(x = 1:10, i = sample(999, 10), length=1000))
#> Formal class 'isparseVector' [package "Matrix"] with 3 slots
#>   ..@ x     : int [1:10] 4 6 7 2 1 3 10 8 9 5
#>   ..@ length: num 1000
#>   ..@ i     : int [1:10] 25 91 245 396 508 510 696 730 859 892

sx <- c(0,0,3, 3.2, 0,0,0,-3:1,0,0,2,0,0,5,0,0)
ss <- as(sx, "sparseVector")
stopifnot(identical(ss,
   sparseVector(x = c(2, -1, -2, 3, 1, -3, 5, 3.2),
                i = c(15L, 10:9, 3L,12L,8L,18L, 4L), length = 20L)))

(ns <- sparseVector(i= c(7, 3, 2), length = 10))
#> sparse vector (nnz/length = 3/10) of class "nsparseVector"
#>  [1] . | | . . . | . . .
stopifnot(identical(ns,
      new("nsparseVector", length = 10, i = c(2, 3, 7))))