我有一个 4 列的矩阵,我对矩阵进行了排序并计算了rowMeans
每一行的矩阵。现在我想用相应的替换原始矩阵中的所有值rowMeans
。c5sub
是 4 列的矩阵
sortmat<-apply(c5sub, 2, sort) # sorted matrix by column
[1,] -7 -6 -17 -6
[2,] -7 -6 -9 -6
[3,] -6 -5 -8 -6
[4,] -6 -5 -8 -6
[5,] -6 -5 -7 -6
[6,] -6 -5 -7 -5
rwmeans<-apply(sortmat, 1, mean)# calculated rowmeans
-9.00 -7.00 -6.25 -6.25 -6.00 -5.75
(a <- sweep(a,1,rwmeans,function(x,y) ifelse(x!=0,y,0)))
[1,] -9.00 -9.00 -9.00 -9.00
[2,] -7.00 -7.00 -7.00 -7.00
[3,] -6.25 -6.25 -6.25 -6.25
[4,] -6.25 -6.25 -6.25 -6.25
[5,] -6.00 -6.00 -6.00 -6.00
[6,] -5.75 -5.75 -5.75 -5.75
我已经使用上面的一个来替换原始值,rowMeans
但它不会替换零,因为我有ifelse
. 如何修改它以替换所有值?