我可以在Excel中轻松做到这一点,但我的数据集太大了。在excel中,我会使用solver。
Column A,B = random numbers
Column C = random number (which I want to maximize the correlation to)
Column D = A*x+B*y where x,y are coefficients resulted from solver
在一个单独的单元格中,我会有correl(C,D)
在求解器中,我会通过改变变量x,y和设置某些约束(例如x,y都必须是正数),将correl(C,D)的目标设置为max。
如何在R中执行此操作?谢谢你的帮助。
在R中,生成一个function
,其输出是要最大化或最小化的值。基本R中包含的一个优化器称为optim()
:
set.seed(1)
A <- runif(100)
B <- runif(100)
C <- runif(100)
# these are your x and y to optimize
pars <- c(x=1,y=1)
OptPars <- function(pars,A,B,C){
D <- A*pars[1]+B*pars[2]
-cor(C,D)
}
# optim is one of many R-ish ways to do Excel's solver
# it minimizes by default (though you can tell it not to)
# and that's why I told it to take -cor()
optim(pars,OptPars,A=A,B=B,C=C)
如果您希望x
和y
具有约束,请将其包含在您正在优化的函数中,例如abs(x)
而不是x
。