I have a matrix with many rows. Let's say
M = matrix(1:20, nrow = 4, ncol = 5)
And I have a threshold variable, e.g.
threshold = c(4,7,11,14,17)
Now I want R to compare each row in the matrix with this threshold value by value and tell me whether at least one value in that row exceeds this threshold's corresponding value. I.e., M[1,1] should be compared with threshold [1], M[1,2] with threshold [2] etc.
Ideally I would like to have a new variable, let's call it check, with just 1/FALSE (there is at least 1 value in the row exceeding the threshold) or 0/TRUE (no such values). Till now, what I could program is this:
check = apply (M, MARGIN=1, (ifelse((M[,] < threshold), 1, 0)))
check = apply (check, MARGIN=1, sum)
check = check == 0
But there are 3 problems with it:
It doesn't work, R says:
check = apply (M, MARGIN=1, (ifelse((M[,] < threshold), 1, 0))) Error in match.fun(FUN) : '(ifelse((M[, ] < threshold), 1, 0))' is not a function, letter or symbol
Even if I perform just
ifelse((M < threshold), 1, 0)
for the first row I get
[1,] 1 1 1 0 0
Which is not true, because there are no values in the first row that exceed the threshold. It seems that R just compares the whole first row with the 1st element of threshold, then the whole 2nd row with the second value etc., and that's not what I want...
Many thanks in advance!
apply(M, 1, function(x) max(diag(sapply(x, function(y) y >threshold))))