recommenderlab, Error in asMethod(object) : invalid class 'NA' to dup_mMatrix_as_geMatrix

StackOverflow https://stackoverflow.com/questions/18580506

  •  27-06-2022
  •  | 
  •  

I am trying to change matrix into a structure that I can use in functions of the recommenderlab package.

datafile1 <- as(datafile1,"matrix")
datafile1
     name1 name2 rating1 rating2 rating3 rating4 rating5 rating6
[1,] "1"   "a"   "0"     "0"     "1"     "0"     "0"     "0"    
[2,] "2"   "d"   "0"     "0"     "1"     "0"     "0"     "0"    
[3,] "3"   "x"   "1"     "0"     "1"     "0"     "0"     "0"    
[4,] "4"   "b"   "0"     "1"     "1"     "0"     "0"     "0"  

library(recommenderlab)
datafile1 <- as(datafile1, "realRatingMatrix")

This is the result:

Error in asMethod(object) : invalid class 'NA' to dup_mMatrix_as_geMatrix

Does anyone have an idea about what's going wrong here?

有帮助吗?

解决方案

The problem is that the RealRatingMatrix class extends Matrix, and Matrix has not implemented matrices with characters in them. Convert your matrix to a numeric first, then convert.

# Recreate data
datafile1<-read.table(textConnection('
name1 name2 rating1 rating2 rating3 rating4 rating5 rating6
"1"   "a"   "0"     "0"     "1"     "0"     "0"     "0"    
"2"   "d"   "0"     "0"     "1"     "0"     "0"     "0"    
"3"   "x"   "1"     "0"     "1"     "0"     "0"     "0"    
"4"   "b"   "0"     "1"     "1"     "0"     "0"     "0"  
'),header=TRUE)
datafile1<-as.matrix(datafile1)

# Convert to numeric (by arbitrarily map the characters to numbers.)
datafile1<-sapply(data.frame(datafile1),as.numeric)

# Create real rating matrix
as(datafile1, "realRatingMatrix")
# 4 x 8 rating matrix of class ‘realRatingMatrix’ with 32 ratings.
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top