Suppose x is defined as
x <- as(c(1,1,0,0,1,0), "sparseVector")
I want to create a diagonal matrix where the diagonal elements are given by the entries in x.
I tried Diagonal(x = x), but I get the following error.
Error in Diagonal(x = x) : 'x' has unsupported class "dsparseVector"
I think you are looking for sparseMatrix. e.g.:
library(Matrix)
x <- c(1,1,0,0,1,0)
x <- sparseMatrix(i = seq(x), j = seq(x), x = x)
x
# 6 x 6 sparse Matrix of class "dgCMatrix"
#
# [1,] 1 . . . . .
# [2,] . 1 . . . .
# [3,] . . 0 . . .
# [4,] . . . 0 . .
# [5,] . . . . 1 .
# [6,] . . . . . 0
To treat zeros in the original vector as sparse elements:
x <- c(1,1,0,0,1,0)
x <- sparseMatrix(i = which(x!=0), j = which(x!=0), x = x[which(x!=0)],
dims = rep(length(x), 2))
x
# 6 x 6 sparse Matrix of class "dgCMatrix"
#
# [1,] 1 . . . . .
# [2,] . 1 . . . .
# [3,] . . . . . .
# [4,] . . . . . .
# [5,] . . . . 1 .
# [6,] . . . . . .
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With