Reputation: 2279
Continuing the question made here, I'd like to add a restriction in the optimization:
a <- c(52.67, 46.80, 41.74, 40.45)
b <- c(1.726219351, 1.842421805, 1.790801758, 1.449997494)
rsq <- function(c) {
x <- log(a)
y <- log((c*(a/b))-1)
summary(lm(y ~ x))$r.squared
}
optimise(rsq, maximum = TRUE, interval=c(1, 1000))
The interval for the optimization is 1 to 1000, however I'd like that the interval starts where
(c*(a/b)) > 0
To avoid problems with log
Upvotes: 0
Views: 34
Reputation: 269501
Just return -Inf if the log argument would be negative. Then it is unnecessary to manipulate the domain.
rsq <- function(c) {
x <- log(a)
tmp <- (c*(a/b))-1
if (any(tmp < 0)) -Inf else summary(lm(log(tmp) ~ x))$r.squared
}
optimise(rsq, maximum = TRUE, interval=c(1, 1000))
giving:
$maximum
[1] 1.082353
$objective
[1] 0.8093781
Fixed.
Upvotes: 1