使用"matrix::sparseMatrix"[R]生成稀疏矩阵时,列的顺序错误



我有一个类似于以下的数据帧:

sparsed <- 
structure(list(Movie = c(1, 1, 1, 2, 2, 2, 3, 3, 3, 3, 3, 4, 
4, 5, 5, 5, 5, 5, 5, 5, 6, 6, 7, 7, 8), User = c(32, 2, 56, 34, 
56, 89, 4, 2, 46, 89, 67, 56, 12, 35, 89, 2, 90, 12, 5, 78, 69, 
32, 64, 56, 2), Rating = c(1L, 3L, 2L, 4L, 5L, 3L, 2L, 3L, 4L, 
5L, 2L, 3L, 5L, 1L, 2L, 3L, 4L, 5L, 4L, 3L, 3L, 2L, 2L, 1L, 1L
)), .Names = c("Movie", "User", "Rating"), row.names = c(NA, 
-25L), class = "data.frame")

将值放入稀疏矩阵的逻辑是什么?为了将其转化为右维(8 x 15(的稀疏矩阵,我必须进行以下奇数转换,否则结果为8 x 90。

library(Matrix)    
sparsed$Movie <- as.factor(as.character(sparsed$Movie))
sparsed$User <- as.factor(as.character(sparsed$User))
sparse <- sparseMatrix(i = as.numeric(sparsed$Movie),
j = as.numeric(sparsed$User),
x = as.numeric(sparsed$Rating))
#8 x 15 sparse Matrix of class "dgCMatrix"
#[1,] . 3 1 . . . . . 2 . . . . . .
#[2,] . . . 4 . . . . 5 . . . . 3 .
#[3,] . 3 . . . 2 4 . . . 2 . . 5 .
#[4,] 5 . . . . . . . 3 . . . . . .
#[5,] 5 3 . . 1 . . 4 . . . . 3 2 4
#[6,] . . 2 . . . . . . . . 3 . . .
#[7,] . . . . . . . . 1 2 . . . . .
#[8,] . 1 . . . . . . . . . . . . .

我现在对这个维度很满意,但矩阵列的顺序不对。例如,第一列对应于电影12而不是2。行的顺序正确地按数字顺序排列。有人能解释一下吗?有什么好方法可以按正确的顺序制作列吗?

sparseMatrix没有做错任何事情。

在将sparsed列最终转换为因子之前,MovieUser是数字,因此2是2,12是12。max(Movie)是8,max(User)是90,所以你会得到一个8x90的矩阵。

一旦您将这些列转换为因子,您是否知道因子级别?

levels(sparsed$Movie)
#[1] "1" "2" "3" "4" "5" "6" "7" "8"
levels(sparsed$User)
#[1] "12" "2"  "32" "34" "35" "4"  "46" "5"  "56" "64" "67" "69" "78" "89" "90"

级别与数字顺序不匹配,例如,12领先于2。如果对这些因素执行as.numeric,则第一个级别"12"将出现在第一个矩阵列中,级别"32"将显示在第三列中。如果您希望它们按正确的数字顺序排列,请使用factor而不是as.factor:控制级别

## take your original `sparsed` data frame, where `User` is numeric
sparsed$User <- as.numeric(
factor(as.character(sparsed$User),
levels = sort(unique(sparsed$User)))
)
## no need to do anything with `Movie` at it's already contiguous numeric from 1
sparse <- sparseMatrix(i = sparsed$Movie,
j = sparsed$User,
x = sparsed$Rating)
#8 x 15 sparse Matrix of class "dgCMatrix"
#                                  
#[1,] 3 . . . 1 . . . 2 . . . . . .
#[2,] . . . . . 4 . . 5 . . . . 3 .
#[3,] 3 2 . . . . . 4 . . 2 . . 5 .
#[4,] . . . 5 . . . . 3 . . . . . .
#[5,] 3 . 4 5 . . 1 . . . . . 3 2 4
#[6,] . . . . 2 . . . . . . 3 . . .
#[7,] . . . . . . . . 1 2 . . . . .
#[8,] 1 . . . . . . . . . . . . . .

最新更新