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?
CodePudding user response:
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
CodePudding user response:
I believe the pmin
method by @caldwellst is the simplest one so far. Here is another option using ifelse
> ifelse(Matrix >= Vector, Vector, Matrix)
[,1] [,2]
[1,] 2 2
[2,] 3 3
[3,] 3 2
[4,] 1 1
CodePudding user response:
It is also possible to do it with dplyr::mutate
.
It is interesting when you have to select a subset of variables.
library(dplyr)
dd = structure(list(V1 = c(3, 3, 5, 1), ` V2` = c(2, 5, 2, 1), Condition = c(2,
3, 3, 3)), class = "data.frame", row.names = c(NA, -4L))
dd %>% mutate(across(contains('V'), ~ifelse(.>=Condition, Condition,. )))
V1 V2 Condition
# 1 2 2 2
# 2 3 3 3
# 3 3 2 3
# 4 1 1 3