Replacing values in a Matrix: in each row, maximum value with minimum value

I can't solve this problem, I am just beginning to learn R. Thanks for the help:

(e) In each row of the matrix replace the maximum value with the minimum value.

Upvotes: 1

Views: 744

Answers (1)

akrun
akrun

Reputation: 887213

We can use apply to loop through the rows (MARGIN = 1) and replace the values that max with the min of that row

t(apply(m1, 1, function(x) replace(x, x== max(x), min(x))))

Or use row/column indexing to assign the elements are max per row to minimum of each row

library(matrixStats)
m1[cbind(seq_len(nrow(m1)), max.col(m1))] <- rowMins(m1)

Or using only base R

m1[cbind(seq_len(nrow(m1)), max.col(m1))] <- m1[cbind(seq_len(nrow(m1)), max.col(-m1))]

data

set.seed(24)
m1 <- matrix(rnorm(5* 10), 5, 10)

Upvotes: 1

Related Questions