Skip to contents

remove_constant() removes zero-variance columns from sparse and dense matrices.

Usage

remove_constant(x)

# S3 method for CsparseMatrix
remove_constant(x)

# S3 method for matrix
remove_constant(x)

Arguments

x

A matrix or CsparseMatrix.

Value

x with zero-variance columns removed.

Details

remove_constant() is an S3 generic with methods for:

  • CsparseMatrix

  • matrix

Examples

# Create a sparse matrix with constant columns
x <- Matrix::rsparsematrix(10, 3, 0.1)
colnames(x) <- paste0("x", 1:3)
x <- cbind(x, "x4" = 1, "x5" = 54)
# Print x
x
#> 10 x 5 sparse Matrix of class "dgCMatrix"
#>       x1   x2      x3 x4 x5
#>  [1,]  . 0.13 .        1 54
#>  [2,]  . .    .        1 54
#>  [3,]  . .    .        1 54
#>  [4,]  . .    .        1 54
#>  [5,]  . .    .        1 54
#>  [6,]  . .    .        1 54
#>  [7,]  . 0.99 .        1 54
#>  [8,]  . .    .        1 54
#>  [9,]  . .    1.3e-05  1 54
#> [10,]  . .    .        1 54

# Same matrix in dense format
xdense <- as.matrix(x)

# Drop constant columns
remove_constant(x)
#> 10 x 2 sparse Matrix of class "dgCMatrix"
#>         x2      x3
#>  [1,] 0.13 .      
#>  [2,] .    .      
#>  [3,] .    .      
#>  [4,] .    .      
#>  [5,] .    .      
#>  [6,] .    .      
#>  [7,] 0.99 .      
#>  [8,] .    .      
#>  [9,] .    1.3e-05
#> [10,] .    .      
remove_constant(xdense)
#>         x2      x3
#>  [1,] 0.13 0.0e+00
#>  [2,] 0.00 0.0e+00
#>  [3,] 0.00 0.0e+00
#>  [4,] 0.00 0.0e+00
#>  [5,] 0.00 0.0e+00
#>  [6,] 0.00 0.0e+00
#>  [7,] 0.99 0.0e+00
#>  [8,] 0.00 0.0e+00
#>  [9,] 0.00 1.3e-05
#> [10,] 0.00 0.0e+00