如何在R中使用带参数的函数

时间:2021-12-05 18:00:29

I am trying to use the optim function in R - I have no problems with this:

我试图在R中使用optim函数 - 我对此没有任何问题:

funk=function(param){
  x=c(1,2,3,4,5)
  z=c(3,4,2,2,1)
  y=c(30,40,22,33,40)
  a=rep(param[1],5)
  b=param[2]
  d=param[3]
  fit=sum((y-(a+b*x+z*d))^2)
  return(fit)
}

optim(par=c(1,1,1),fn=funk)
#

But as soon as I don't want to hard-code my data (x,y,z) into the function I have problems. How do I optimize a function in optim when the function input is more than just the parameters to be optimized? Ideally I would pass on value of xx, zz, yy then optimize, then move to differnt values of xx, zz, yy and optimize that case next.

但是一旦我不想将我的数据(x,y,z)硬编码到函数中我就会遇到问题。当函数输入不仅仅是要优化的参数时,如何优化函数优化?理想情况下,我会传递xx,zz,yy的值然后进行优化,然后移动到xx,zz,yy的不同值并接下来优化该情况。

xx=c(1,2,3,4,5)
zz=c(3,4,2,2,1)
yy=c(30,40,22,33,40)

funk=function(param,x,y,z){
  a=rep(param[1],5)
  b=param[2]
  d=param[3]
  fit=sum((y-(a+b*x+z*d))^2)
  return(fit)
}

optim(par=c(1,1,1),fn=funk(param=c(0,0,0),x=xx,y=yy,z=zz))

Error in (function (par) : could not find function "fn"

(函数(par)中的错误:找不到函数“fn”

1 个解决方案

#1


18  

In optim, ... is used to pass arguments to fn:

在optim中,...用于将参数传递给fn:

xx=c(1,2,3,4,5)
zz=c(3,4,2,2,1)
yy=c(30,40,22,33,40)

funk=function(param,x,y,z){
  a=rep(param[1],5)
  b=param[2]
  d=param[3]
  fit=sum((y-(a+b*x+z*d))^2)
  return(fit)
}

optim(par=c(1,1,1), fn=funk, x=xx, y=yy, z=zz) 
$par
[1] -1.863076  5.722988  7.372296

$value
[1] 124.075

$counts
function gradient 
     180       NA 

$convergence
[1] 0

$message
NULL

#1


18  

In optim, ... is used to pass arguments to fn:

在optim中,...用于将参数传递给fn:

xx=c(1,2,3,4,5)
zz=c(3,4,2,2,1)
yy=c(30,40,22,33,40)

funk=function(param,x,y,z){
  a=rep(param[1],5)
  b=param[2]
  d=param[3]
  fit=sum((y-(a+b*x+z*d))^2)
  return(fit)
}

optim(par=c(1,1,1), fn=funk, x=xx, y=yy, z=zz) 
$par
[1] -1.863076  5.722988  7.372296

$value
[1] 124.075

$counts
function gradient 
     180       NA 

$convergence
[1] 0

$message
NULL