[R] Functions ,Optim, & Dataframe

Tony Plate tplate at acm.org
Mon Jul 31 19:52:14 CEST 2006


Supply your additional arguments to optim() and they will get passed to 
your function:

 > mydat<-data.frame(d1=c(3,5),d2=c(6,10),p1=c(.55,.05),p2=c(.85,.35))
 >
 > fr<-function(x, d) {
+     # d is a vector of d1, d2, p1 & p2
+     u <- x[1]
+     v <- x[2]
+     d1 <- d[1]
+     d2 <- d[2]
+     p1 <- d[3]
+     p2 <- d[4]
+     sqrt(sum((plnorm(c(d1,d2,u,v)-c(p1,p2))^2)))
+ }
 > x0 <- c(1,1)    # starting values for two unknown parameters
 > y1 <- optim(x0,fr,d=unlist(mydat[1,]))
 > y2 <- optim(x0,fr,d=unlist(mydat[2,]))
 > y1$par
[1] 0.462500 0.828125
 > y2$par
[1] -1.0937500  0.2828125
 > yall <- apply(mydat, 1, function(d) optim(x0,fr,d=d))
 > yall[[1]]$par
[1] 0.462500 0.828125
 > yall[[2]]$par
[1] -1.0937500  0.2828125
 >

One thing you must be careful of is that none of the arguments to your 
function match or partially match the named arguments of optim(), which are:
 > names(formals(optim))
[1] "par"     "fn"      "gr"      "method"  "lower"   "upper"   "control"
[8] "hessian" "..."
 >

For example, if your function has an argument 'he=', you will not be 
able to pass it, because if you say optim(x0, fr, he=3), the 'he' will 
match the 'hessian=' argument of optim(), and it will not be interpreted 
as being a '...' argument.

-- Tony Plate

Michael Papenfus wrote:
> I think I need to clarify a little further on my original question.
> 
> I have the following two rows of data:
> mydat<-data.frame(d1=c(3,5),d2=c(6,10),p1=c(.55,.05),p2=c(.85,.35))
>  >mydat
>   d1 d2 p1 p2
> 1 3 6 0.55 0.85
> 2 5 10 0.05 0.35
> 
> I need to optimize the following function using  optim for each row in mydat
> fr<-function(x) {
>     u<-x[1]
>     v<-x[2]
>     sqrt(sum((plnorm(c(d1,d2,u,v)-c(p1,p2))^2))
> }
> x0<-c(1,1)    # starting values for two unknown parameters
> y<-optim(x0,fr)
> 
> In my defined function fr, (d1 d2 p1 p2) are known values which I need 
> to read in from my dataframe and u & v are the TWO unknown parameters.  
> I want to solve this equation for each row of my dataframe.
> 
> I can get this to work when I manually plug in the known values (d1 d2 
> p1 p2).  However, I would like to apply this to each row in my dataframe 
> where the known values are automatically passed to my function which 
> then is sent to optim which solves for the two unknown parameters for 
> each row in the dataframe.
> 
> thanks again,
> mike
>



More information about the R-help mailing list