Reputation: 13
For example, I have a 3x3 matrix called "A" with numbers between 1 to 10, and a constant= 5. I would like to create another matrix 3x3 called "B" where each element is the minimum between A elements and the constant. I know i could do this easily with for loops, but is there any function or shorter way to do this?
example
A[1,1] = 2 -> B[1,1]=min(A[1,1],constant) ->B[1,1]=2
A[1,2]=10 -> B[1,2]=min(A[1,2],constant) ->B[1,2]=5
Upvotes: 1
Views: 124
Reputation: 388962
You can use pmin
:
set.seed(123)
A <- matrix(sample(1:10, 9), nrow = 3)
constant <- 5
pmin(A, constant)
# [,1] [,2] [,3]
#[1,] 3 5 1
#[2,] 5 5 5
#[3,] 2 5 5
Upvotes: 1