Search code examples
rallocationraster

Allocate values of one column after the modolus/values of another column


In order to distribute a certain amount of TRUE (=1) values, depending on raster layer's values, I would like to do something like this:

Let's say I have a 9x2 matrix looking like this:

Example <- matrix(c(0.8,0.6,0.5,0.3,0.2,0.4,0.9,0.7,
                0.1,1,1,1,1,1,0,0,0,0),ncol=2)

     > Example
      [,1] [,2]
 [1,]  0.8    1
 [2,]  0.6    1
 [3,]  0.5    1
 [4,]  0.3    1
 [5,]  0.2    1
 [6,]  0.4    0
 [7,]  0.9    0
 [8,]  0.7    0
 [9,]  0.1    0

Now I want to allocate the 1's from [,2] as a function of the highest values of [,1] without changing the order of [,1]. The result should look like this:

> Example
      [,1] [,2]
 [1,]  0.8    1
 [2,]  0.6    1
 [3,]  0.5    1
 [4,]  0.3    0
 [5,]  0.2    0
 [6,]  0.4    0
 [7,]  0.9    1
 [8,]  0.7    1
 [9,]  0.1    0

Is there any elegant way to do this. I could't find any function to solve this problem. As I want to convert [,2] to a raster layer using the raster package a raster-based solution would work for me as well.


Solution

  • You can find how many 1's you have by summing column 2. You can then find your relative threshold of column 1 by checking if it is higher or lower than that value.

    how.many.ones <- sum(Example[, 2])
    
    max.thresh <- sort(Example[, 1], decreasing=TRUE)[how.many.ones]
    
    change.to.one <- Example[, 1] >= max.thresh
    
    Example[, 2] <- ifelse(change.to.one, 1, 0)
    

    RESULTS:

    Example
    
          [,1] [,2]
     [1,]  0.8    1
     [2,]  0.6    1
     [3,]  0.5    1
     [4,]  0.3    0
     [5,]  0.2    0
     [6,]  0.4    0
     [7,]  0.9    1
     [8,]  0.7    1
     [9,]  0.1    0
    


    Caveat:

    There is no tie-handling in this process.