Re: [R] Help with matrix manipulation

From: Robin Hankin <r.hankin_at_noc.soton.ac.uk>
Date: Fri 28 Jul 2006 - 17:02:54 EST

Hi

two solutions, your best option depends on the level of generality you need.

(i)

M[M< -4] <- -4
M[M > 3] <- 3

(ii)

M <- pmax(pmin(M,3),-4)

HTH rksh

On 28 Jul 2006, at 07:44, Kartik Pappu wrote:

> Hi all,
>
> I have a square (a x a) matrix with values in a range. For example:
>
> [,1] [,2] [,3] [,4]
> [1,] -5 -1 3 -4
> [2,] -4 0 4 -3
> [3,] -3 1 5 -2
> [4,] -2 2 -5 -1
>
> I want to take any number smaller than -4 (in this example -5) and
> replace it with -4 and similarly take any number greater than 3 (in
> this case 4 and 5) and replace it with 3. The other numbers (and the
> overall structure of the matrix should remain unchanged.
>
> Seems like something that would use an "if a<b then c else d" kind of
> logic, but I cannot figure out how to manipulate the entire matrix.
>
> Thanks much
>
> Kartik
>
> ______________________________________________
> R-help@stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-
> guide.html
> and provide commented, minimal, self-contained, reproducible code.

--
Robin Hankin
Uncertainty Analyst
National Oceanography Centre, Southampton
European Way, Southampton SO14 3ZH, UK
  tel  023-8059-7743

______________________________________________
R-help@stat.math.ethz.ch mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.
Received on Fri Jul 28 17:08:50 2006

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.1.8, at Fri 28 Jul 2006 - 18:18:43 EST.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.