我有4个评分者(行)的电影(列)等级排序矩阵:
n<-8
M<-c(2,4,1,7,6,5,3,8,
2,3,1,6,5,4,0,7,
1,3,6,8,6,4,2,7,
2,4,3,7,5,0,1,6)
M<-matrix (M, ncol=n, byrow = TRUE)
我想创建两个新的矩阵,显示每个元素的排名较差的数量和更好的排名数量。例如,有1部电影比2级更好,6部更差。
我的困难在于我想忽略0元素并相应地对结果矩阵进行加权,以便得到:
u <- c(6,4,7,1,2,3,5,0, # 'worse' matrix
5,4,6,1,2,3,0,0,
7,5,2,0,2,4,6,1,
5,3,4,0,2,0,6,1)
v <-c(1,3,0,6,5,4,2,7, # 'better' matrix
1,2,0,5,4,3,0,6,
0,2,5,7,5,3,1,6,
1,3,2,6,4,0,0,5)
这是我的尝试丑陋的尝试让我接近但不忽略0。
rowSums(M>0)
sumsOfRows<-rowSums(M>0)
sumsOfRows[1]-(M[1,])
sumsOfRows[2]-(M[2,]) ## need to ignore the zero
sumsOfRows[3]-(M[3,])
sumsOfRows[4]-(M[4,]) ## need to ignore the zero
(M[1,])-1
(M[2,])-1 ## need to ignore the zero
(M[3,])-1
(M[4,])-1 ## need to ignore the zero
urow1<-sumsOfRows[1]-(M[1,])
urow2<-sumsOfRows[2]-(M[2,]) ## need to ignore the zero
urow3<-sumsOfRows[3]-(M[3,])
urow4<-sumsOfRows[4]-(M[4,]) ## need to ignore the zero
u<-matrix(c(urow1,urow2,urow3,urow4), ncol=n, byrow = TRUE)
vrow1<-(M[1,])-1
vrow2<-(M[2,])-1 ## need to ignore the zero
vrow3<-(M[3,])-1
vrow4<-(M[4,])-1 ## need to ignore the zero
v<-matrix(c(vrow1,vrow2,vrow3,vrow4), ncol=n, byrow = TRUE)
答案 0 :(得分:0)
根据上面的评论和其他一些快捷方式,我的问题是一个有效的答案。
M<-c(2,4,1,7,6,5,3,8,
2,3,1,6,5,4,0,7,
1,3,6,8,6,4,2,7,
2,4,3,7,5,0,1,6)
M<-matrix (M, ncol=8, byrow = TRUE)
M[M==0]<-NA;apply(M,1,rank,na.last="keep")
rowSums(M>0, na.rm = TRUE)
sumsOfRows<-rowSums(M>0, na.rm = TRUE)
u<-abs(sweep(M,MARGIN=1,sumsOfRows,`-`))
v<-abs(sweep(M,MARGIN=1,1,`-`))
u[is.na(u)] <- 0;u
v[is.na(v)] <- 0;v