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

Jinsong Zhao jszhao at yeah.net
Tue Aug 12 00:27:36 CEST 2014


On 2014/8/11 14:50, William Dunlap wrote:
> You can use
>      m[m > 0 & m <= 1.0] <- 1
>      m[m > 1 ] <- 2
> or, if you have lots of intervals, something based on findInterval().  E.g.,
>      m[] <- findInterval(m, c(-Inf, 0, 1, Inf)) - 1
>
> (What do you want to do with non-positive numbers?)
>
> Bill Dunlap
> TIBCO Software
> wdunlap tibco.com

Thank you very much.

I think findInterval() is what I want.

Regards,
Jinsong

>
>
> On Mon, Aug 11, 2014 at 2: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
>> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
>> and provide commented, minimal, self-contained, reproducible code.
>



More information about the R-help mailing list