提取矩阵元素中的秩差

Extracting rank differences in matrix elements

我有一个由 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)

根据上面的评论和其他一些快捷方式,这是对我的问题的有效答案。

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