sparseMatrix(i = svd[[1]], j = svd[[2]], x = svd[[3]])
Error in validObject(r) :
无效的类“dgTMatrix”对象:TsparseMatrix中的所有列索引(slot'j')必须介于0和ncol-1之间
我有一个如下所示的数据集
id p1 p2 p3 p4
a 10 20 30 40
b 32 45 65 54
c 54 56 12 45
d 21 34 65 44
答案 0 :(得分:0)
尝试
library(Matrix)
library(reshape2)
svd$id <- as.numeric(factor(svd$id))
sM <- transform(melt(svd, id.var='id', na.rm=TRUE),
variable=match(variable, names(svd)[-1]))
with(sM, sparseMatrix(id, variable, x=value))
svd <- structure(list(id = c("a", "b", "c", "d"), p1 = c(10L, 32L, 54L,
21L), p2 = c(20L, 45L, 56L, 34L), p3 = c(30L, 65L, 12L, 65L),
p4 = c(40L, 54L, 45L, 44L)), .Names = c("id", "p1", "p2",
"p3", "p4"), class = "data.frame", row.names = c(NA, -4L))