[R] Help with matrix manipulation
Simon Blomberg
blomsp at ozemail.com.au
Fri Jul 28 09:14:37 CEST 2006
apply is your friend:
fn <- function (x, a, b) {
if (x < a) return(a) else
if (x > b) return(b) else
x
}
apply(mat, c(1,2), fn, -4, 3)
[,1] [,2] [,3] [,4]
[1,] -4 -1 3 -4
[2,] -4 0 3 -3
[3,] -3 1 3 -2
[4,] -2 2 -4 -1
HTH,
Simon.
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 at 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.
>
>
--
Simon Blomberg, B.Sc.(Hons.), Ph.D, M.App.Stat.
Centre for Resource and Environmental Studies
The Australian National University
Canberra ACT 0200
Australia
T: +61 2 6125 7800 email: Simon.Blomberg_at_anu.edu.au
F: +61 2 6125 0757
CRICOS Provider # 00120C
More information about the R-help
mailing list