# [R] Adding weights to optim

Rolf Turner rolf.turner at xtra.co.nz
Sat Sep 24 03:10:08 CEST 2011

```
I'm not at all sure that I understand your question, but since (as far
as I am aware) no-one else has answered, I'll give it a go.

The puzzle, to me, is what you mean by ``I would like to add weights
to optim.''  What do you mean ``add weights''?

If you want to minimize a weighted sum of squares, it seems to me to
be trivial:

logis.op <- function(p,x,y,w=1) {
ypred <- 1.0 / (1.0 + exp((p[1] - x) / p[2]));
sum(w*(y-ypred)^2)
}

(Note that your ``res <- ...'' and ``return(res)'' are unnecessary.)

optim(c(0.0,1.0),logis.op,x=d1_all\$SOA,y=as.numeric(md1[,i]),
w=<whatever weights you had in
mind>)

HTH

cheers,

Rolf Turner

On 23/09/11 13:47, Ahnate Lim wrote:
> I realize this may be more of a math question. I have the following optim:
>
> optim(c(0.0,1.0),logis.op,x=d1_all\$SOA,y=as.numeric(md1[,i]))
>
> which uses the following function:
>
> logis.op<- function(p,x,y) {
>
>    ypred<- 1.0 / (1.0 + exp((p[1] - x) / p[2]));
>
> res<- sum((y-ypred)^2)
>
>      return(res)
>
> }
>
> I would like to add weights to the optim. Do I have to alter the logis.op
> function by adding an additional weights parameter? And if so, how would I
> change the ypred formula? Would I just substitute x with x*w

```

More information about the R-help mailing list