I have a matrix and a vector like this:
Matrix<-cbind(c(3,3,5,1),c(2,5,2,1))
Vector<-c(2,3,3,3)
I want to replace the Matrix elements that are >= the corresponding Vector value with the values in the Vector so that the Matrix would now look like this:
MatrixNew<-cbind(c(2,3,3,1),c(2,3,2,1))
What logic would achieve this?
Thought you had to use apply(Matrix, \(x) pmin(x, Vector))
, but actually, you can just use pmin()
directly on your Matrix
because it will recycle the Vector
to match the length.
pmin(Matrix, Vector)
#> [,1] [,2]
#> [1,] 2 2
#> [2,] 3 3
#> [3,] 3 2
#> [4,] 1 1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With