One has a matrix Lambda
with p
columns and n
rows and for each row wants assign all the values to 0
except the value in the first column and the maximum of the values in the other columns (in that sense all the p - 2
minimum values after avoiding the first column).
For the moment I am doing this with a for
loop, like follows:
set.seed(60)
(Lambda = matrix(sample.int(30),5))
[,1] [,2] [,3] [,4] [,5] [,6]
[1,] 19 20 27 18 15 25
[2,] 16 28 1 4 22 7
[3,] 2 10 8 23 3 12
[4,] 5 6 9 17 11 29
[5,] 26 30 24 13 14 21
m <- ncol(Lambda) - 2
for(ir in seq_len(nrow(Lambda))){
Lambda[ir, match(tail(sort(abs(Lambda[ir, 2:ncol(Lambda)]), decreasing = TRUE), m), Lambda[ir,])] <- 0
}
Lambda
[,1] [,2] [,3] [,4] [,5] [,6]
[1,] 19 0 27 0 0 0
[2,] 16 28 0 0 0 0
[3,] 2 0 0 23 0 0
[4,] 5 0 0 0 0 29
[5,] 26 30 0 0 0 0
Fine, one gets the goal, but if there were many rows it would become a problem. Is there a solution not using a for
loop? It could be with lapply
but I'm not sure if it would be really efficient. Maybe with data.table
after converting the matrix?
Thank you!