Search code examples
rmatrixvectorizationdata-comparison

Row wise comparison of a matrix with a vector in R using vectorization


I want to compare each row of a matrix with a vector and generate an index of the first value from the ith row that is less than the ith value in the vector. The values in each row of the matrix are sorted in decreasing order. Since the number of rows is very large, I am looking for a vectorized solution and would want to avoid loops and apply function.

For example, if I want to compare the following matrix M and vector v, then the output should be (3,2,3,NA).

M = matrix(c(10.2,11.0,10,9.5,9.2,8.9,7.6,8.4,5.4,5.6,6.5,7.2),4,3)
M
     [,1] [,2] [,3]
[1,] 10.2  9.2  5.4
[2,] 11.0  8.9  5.6
[3,] 10.0  7.6  6.5
[4,]  9.5  8.4  7.2

v <- c(8.4,9.5,7.0,6.0)

The output should be (3,2,3,NA).

When I use 'which' function in R, it works for each row but is not vectorized.

which(M[2,]<v[2])[1]
2

which(M[3,]<v[3])[1]
3

Thank you!


Solution

  • The vectorized option would be max.col

    max.col(M < v, 'first') *NA^!rowSums(M < v)
    #[1]  3  2  3 NA