I am trying to estimate a set of parameters using a genetic algorithm in R with the 'GA' package. So far I am doing something very simple (which works):
library(GA)
df <- data.frame(DM=c(1000,1500),
c1=c(50,75),
c2=c(90,105))
func <- function(x1, x2, theta) theta[1]*x1 + theta[2]*x2
fitnessL2 <- function(theta, x1, x2, y) {
f <- -sum((y - func(x1, x2, theta))^2)
}
GA2 <- ga(type = "real-valued", fitness = fitnessL2,
x1 = df$c1, x2 = df$c2, y = df$DM, names = c("a", "b"),
min = c(0, 0), max = c(100, 100))
which produces values for a,b.
However, I want to constrain a and b not individually, but as something like
a + b == 20.
Can someone please let me know if this is possible?
Thanks in advance.
Best Answer
If you have $a+b=20$, you have only one parameter, say $a$; the second is just $20-a$. This way you only need to tweak the function a bit and you are left with a single, simple constraint over $a$.