Home > Blockchain >  Assign integer values with a certain sum based on column values
Assign integer values with a certain sum based on column values

Time:01-12

I am assigning traps to locations with certain establishment risks for pests. I have calculated the risk of establishment per site. I would like to find an efficient and safe method to assign a certain number of traps to the sites (for example 10 sites in total). This means I have to multiply the risk values with a certain value until the sum of all integers is the value I am looking for (10, for example).

Is there a way to do this in R?

Example:

example <- NULL
example$site <- c("a", "b", "c", "d")
example$est_risk <- c(0.001,0.05,0.07,0.1)
example <- as.data.frame(example)

gives

enter image description here

and I am looking for a convenient way to get

enter image description here

I have many more sites, and will also need to do it for various pests, so doing it manually is cumbersome and error-prone. Thank you for your help.

CodePudding user response:

This solution starts with 0 traps assigned, then adds them to sites one at a time such that after each addition the Euclidean distance between distribution of the traps and the distribution of the risk is minimised.

trapsDistribtion <- function(risk, N){
x <- rep(0,length(risk))
for(i in 1:N){
j = which.min(sapply(seq_along(risk), \(i) {
  y = x
  y[i] = y[i] 1
  sum(((risk/sum(risk)) - (y/sum(y)))^2)
  }))
x[j] <- x[j] 1
}
 
x
}



> trapsDistribtion(c(0.001,0.05,0.07,0.1),10)
[1] 0 2 3 5

  • Related