How to find the maximum value of a function changing one constant value in R?

 ̄綄美尐妖づ 提交于 2019-12-24 21:42:26

问题


I have the following linearized plot:

a and b are vectors with data, c is a constant. The task is find a value of c that maximizes R^2 for a linear regression

a <- c(56.60, 37.56, 15.80, 27.65, 9.20, 5.05, 3.54)
b <- c(23.18, 13.49, 10.45, 7.24, 5.44, 4.19, 3.38)
c <- 1

x <- log(a)
y <- log((c*(a/b))-1)

rsq <- function(x, y) summary(lm(y~x))$r.squared
rsq(x, y)

optimise(rsq, maximum = TRUE)

回答1:


This works:

a <- c(56.60, 37.56, 15.80, 27.65, 9.20, 5.05, 3.54)
b <- c(23.18, 13.49, 10.45, 7.24, 5.44, 4.19, 3.38)

rsq <- function(c) {
  x <- log(a)
  y <- log((c*(a/b))-1)
  stopifnot(all(is.finite(y)))  
  summary(lm(y ~ x))$r.squared
}
optimise(rsq, maximum = TRUE, interval=c(0.8, 3))

.

# > optimise(rsq, maximum = TRUE, interval=c(0.8, 3))
# $maximum
# [1] 1.082352
# 
# $objective
# [1] 0.8093781

You can also have a nice plot:

plot(Vectorize(rsq), .8, 3)
grid()

To set a condition for the observations you can do

rsq <- function(c) {
  xy <- data.frame(a=a, y=(c*(a/b))-1)
  summary(lm(log(y) ~ log(a), data=subset(xy, y>0)))$r.squared
}
optimise(rsq, maximum = TRUE, interval=c(0.1, 3))

... and the interesting plot:

plot(Vectorize(rsq), .3, 1.5)
grid()

rsq(0.4) 


来源:https://stackoverflow.com/questions/57146134/how-to-find-the-maximum-value-of-a-function-changing-one-constant-value-in-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!