如何找到在R中改变一个常数的函数的最大值? [英] How to find the maximum value of a function changing one constant value in R?
本文介绍了如何找到在R中改变一个常数的函数的最大值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下线性化的图:
a
和b
是带有数据的向量,c
是常数.任务是找到一个c
值,该值使R^2
最大化以进行线性回归
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)
推荐答案
这有效:
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()
要为观察设置条件
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)
这篇关于如何找到在R中改变一个常数的函数的最大值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文