Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write an apply() function to limit each element in a matrix column to a maximum allowable value?

Tags:

r

apply

I'm trying to learn how to use the apply() functions.

Suppose we have a 3 row, 2 column matrix of test <- matrix(c(1,2,3,4,5,6), ncol = 2), and we would like the maximum value of each element in the first column (1, 2, 3) to not exceed 2 for example, so we end up with a matrix of (1,2,2,4,5,6).

How would one write an apply() function to do this?

Here's my latest attempt: test1 <- apply(test[,1], 2, function(x) {if(x > 2){return(x = 2)} else {return(x)}})

like image 614
Curious Jorge - user9788072 Avatar asked Dec 31 '25 17:12

Curious Jorge - user9788072


2 Answers

We may use pmin on the first column with value 2 as the second argument, so that it does elementwise checking with the recycled 2 and gets the minimum for each value from the first column

test[,1] <- pmin(test[,1], 2)

-output

> test
     [,1] [,2]
[1,]    1    4
[2,]    2    5
[3,]    2    6

Note that apply needs the 'X' as an array/matrix or one with dimensions, when we subset only a single column/row, it drops the dimensions because drop = TRUE by default

like image 176
akrun Avatar answered Jan 02 '26 10:01

akrun


If you really want to use the apply() function, I guess you're looking for something like this:

t(apply(test, 1, function(x) c(min(x[1], 2), x[2])))
##       [,1] [,2]
##  [1,]    1    4
##  [2,]    2    5
##  [3,]    2    6

But if you want my opinion, akrun's suggestion is definitely better.

like image 25
J.P. Le Cavalier Avatar answered Jan 02 '26 09:01

J.P. Le Cavalier



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!