# [R] efficient way to replace a range of numeric with a integer in a matrix

Richard M. Heiberger rmh at temple.edu
Mon Aug 11 23:43:49 CEST 2014

```(m>1)+1

On Mon, Aug 11, 2014 at 5:40 PM, Jinsong Zhao <jszhao at yeah.net> wrote:
> Hi there,
>
> I hope to replace a range of numeric in a matrix with a integer. For
> example, in the following matrix, I want to use 1 to replace the elements
> range from 0.0 to 1.0, and all larger than 1. with 2.
>
>> (m <- matrix(runif(16, 0, 2), nrow = 4))
>           [,1]       [,2]      [,3]     [,4]
> [1,] 0.7115088 0.55370418 0.1586146 1.882931
> [2,] 0.9068198 0.38081423 0.9172629 1.713592
> [3,] 1.5210150 0.93900649 1.2609942 1.744456
> [4,] 0.3779058 0.03130103 0.1893477 1.601181
>
> so I want to get something like:
>
>      [,1] [,2] [,3] [,4]
> [1,]    1    1    1    2
> [2,]    1    1    1    2
> [3,]    2    1    2    2
> [4,]    1    1    1    2
>
> I wrote a function to do such thing:
>
> fun <- function(x) {
>     if (is.na(x)) {
>         NA
>     } else if (x > 0.0 && x <= 1.0) {
>         1
>     } else if (x > 1.0) {
>         2
>     } else {
>         x
>     }
> }
>
> Then run it as:
>
>> apply(m,2,function(i) sapply(i, fun))
>
> However, it seems that this method is not efficient when the dimension is
> large, e.g., 5000x5000 matrix.
>
> Any suggestions? Thanks in advance!
>
> Best regards,
> Jinsong
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help