我可以在 Excel 中轻松完成此操作,但我的数据集太大了。在 excel 中,我会使用求解器。
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)
在求解器中,我会将 correl(C,D) 的目标设置为最大值,方法是更改变量 x,y 并设置某些约束(例如 x,y 都必须是正数)。
我怎样才能在 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
.
关于excel - 在 R 中,如何找到最佳变量以最大化或最小化两个数据集之间的相关性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9570328/