How about the next
set.seed(2017)
# Sample data
mat <- matrix(sample(5*10), ncol = 5)
mat;
# [,1] [,2] [,3] [,4] [,5]
# [1,] 47 49 42 46 11
# [2,] 27 1 41 38 37
# [3,] 23 39 40 28 13
# [4,] 14 16 21 4 43
# [5,] 36 18 6 33 9
# [6,] 35 50 48 10 29
# [7,] 2 45 15 22 7
# [8,] 19 24 8 34 5
# [9,] 20 31 44 3 25
#[10,] 12 26 32 30 17
# Scale by row length if row does not contain 1
mat.scaled <- t(apply(mat, 1, function(x) if (1 %in% x) x else x / length(x)))
mat.scaled;
# [,1] [,2] [,3] [,4] [,5]
# [1,] 9.4 9.8 8.4 9.2 2.2
# [2,] 27.0 1.0 41.0 38.0 37.0
# [3,] 4.6 7.8 8.0 5.6 2.6
# [4,] 2.8 3.2 4.2 0.8 8.6
# [5,] 7.2 3.6 1.2 6.6 1.8
# [6,] 7.0 10.0 9.6 2.0 5.8
# [7,] 0.4 9.0 3.0 4.4 1.4
# [8,] 3.8 4.8 1.6 6.8 1.0
# [9,] 4.0 6.2 8.8 0.6 5.0
#[10,] 2.4 5.2 6.4 6.0 3.4
source
share