我有以下向量:
a <- 1:10
b <- c(100, 300, 400, 120, 131,
450, 400, 432, 111, 123)
rep_ab <- unlist(lapply(a, function(x) rep(x, times = b[x])))
length(rep_ab) == sum(b)
# TRUE
I would like to create a distance matrix using the vector `rep_ab`. Usually, I would use the following code:
mat <- outer(rep_ab, rep_ab, FUN = "-")
但是由于这个矩阵太大,我想使用稀疏矩阵创建这个距离矩阵。我有办法做到这一点吗?
提前致谢。
library(Matrix)
a <- 1:10
b <- c(100, 300, 400, 120, 131, 450, 400, 432, 111, 123)
rep_ab <- unlist(lapply(a, function(x) rep(x, times = b[x])))
# Create a sparse matrix with 0 values
sparse_matrix <- Matrix(0, nrow = length(rep_ab), ncol = length(rep_ab), sparse = TRUE)
# Fill the sparse matrix with distance values
for (i in 1:length(rep_ab)) {
for (j in 1:length(rep_ab)) {
sparse_matrix[i, j] <- abs(rep_ab[i] - rep_ab[j])
}
}
# Convert to a sparse distance matrix
sparse_distance_matrix <- as(sparse_matrix, "CsparseMatrix")
print(sparse_distance_matrix)