This is an elementary question; I apologize for it.
Let x <- c(1,2,3,4,5)
. I would like to produce a vector z
of length 5 s.t. its components are all those x
satisfying the condition
if x[i]>2
then write 2
.
The result should look like
z <- c(1,2,2,2,2)
I know that
z <- which(x>2)
gives me
3 4 5
but I cannot find a good way to implement it to arrive at the result. I thank you all for your support.
EDIT. If instead of considering a vector x
I have a matrix M
with columns x
and y
and I want to apply the above trimming to the column x
leaving y
untouched, how should I proceed?
For example:
y <- x
y[x>2] <- 2
1 2 2 2 2
If you've a matrix M
with two columns, and you want to replace only the first column with values > 2 to 2, then do:
M[,1][M[,1]>2] <- 2