How to use a function with parameters in R

I am trying to use the optimization function in R - I have no problem with this:

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) in a function, I have problems. How to optimize a function in optimization mode when inputting a function is more than just optimizable parameters? Ideally, I would pass the value xx, zz, yy, then optimize, and then move to different values ​​xx, zz, yy and optimize the following case.

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"

+4
source share
1 answer

B optim, ...used to pass arguments 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
+15

Source: https://habr.com/ru/post/1547526/


All Articles