Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In R how would you replace values in a matrix that have a certain condition with values from another vector?

Tags:

r

vector

matrix

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?

like image 989
locket Avatar asked Sep 17 '25 00:09

locket


1 Answers

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
like image 126
caldwellst Avatar answered Sep 18 '25 15:09

caldwellst



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!