Min (greater than 0) from column combined with row operation
I am trying to get the minimum value (greater than 0) from a column in a matrix and then use the row number where that minimum value is to calculate the value that applies (as a formula) to all rows below the minimum row (identified earlier).
Let me demonstrate with an example: If I define x as:
x<-rbind(c(0, 0, 0), c(0,0,3), c(0,3,5))
such that x
:
[,1] [,2] [,3]
[1,] 0 0 0
[2,] 0 0 3
[3,] 0 3 5
then I would like to point out that column 1 has no minimum, column 2 has a minimum at index 3, and column 3 has a minimum at index 2.
So, I created the following attempt at creating a vector of minimums:
min<-apply(x,2,function (v) min(which(v>0), na.rm = TRUE))
This gives me a warning:
Warning message:
In min(which(v > 0), na.rm = TRUE) :
no non-missing arguments to min; returning Inf
(problem 1): Which I don't know how to avoid.
(problem 2): Now I need to take the results of the minimum (where it exists) and calculate the value of the function based on the value of the vector min, and also use the index of the vector min to select the value from another matrix st
This I played around a bit without resorting to loops, not sure , how to do it.
Going back to the example, the first value in min
is equal Inf
, so my vector calc.results
gets 0, the next value in min
is 3, so from the matrix st
I would like to select the third row in the second column (3) and then use that value to calculate the result for the 2nd column in calc.results
, etc. After the operation completes, it calc.results
will look something like this (for example, simplicity, nothing done with a value from st
):
[1] 0 3 3
Then I need to apply calc.results
to the matrix st
, subtracting the value calc.results
only after I have reached the row specified earlier in min
(with index min
equal to the column st
) All other rows are left untouched.
In this example, the end result will look something like this:
[,1] [,2] [,3]
[1,] 0 0 0
[2,] 0 0 0
[3,] 0 0 2
since in the second column the value min
is 3 and the value calc.results
is 3 in the second column, st
has 3 subtracted in the 2nd column only in row 3, etc. (note that the fact that the columns are zeroed out is a product of this example and not generally true).
source to share
task (1)
the warning is caused by the fact that you are min
not accepting numbers, namelyinteger(0)
# try this to see the warning clearly:
min(integer(0))
# try this to see where you are getting integer(0)
apply(x,2,function (v) which(v>0))
To avoid the warning, you can add an if-statement to function(v)
, for example:
apply(x, 2, function (v) min(ifelse(any(v>0), which(v>0), 0), na.rm = TRUE))
however, keep in mind that this is just a warning, and as long as you are aware of what exactly is causing it, you do not need to worry about it.
source to share