[R] How to get the minimum ?
Christoph Buser
buser at stat.math.ethz.ch
Thu Jul 7 17:04:15 CEST 2005
Dear Philipe
You can use optimize (see ?optimize), e.g. :
funToMin <- function(x, data, a = 1, b = 1) {
sum((data[data[,"group"]=="A","y"] - x)^2) +
sum((data[data[,"group"]=="B","y"] - a*x - b)^2)
}
dat <- data.frame(y = rnorm(100), group = rep(c("A","B"), each = 50))
(m <- optimize(function(x) funToMin(x,dat), interval = c(-10,10)))
Please be careful. This function is only for demonstration
issue. It is bad programmed. It works if x is only 1 number,
but if you call the function, using a vector instead of a single
number (and I do not prevent this by checking it), you will get
warnings or errors. Therefore it will be better to use your own,
hopefully better programmed function in optimize.
Regards,
Christoph Buser
--------------------------------------------------------------
Christoph Buser <buser at stat.math.ethz.ch>
Seminar fuer Statistik, LEO C13
ETH (Federal Inst. Technology) 8092 Zurich SWITZERLAND
phone: x-41-44-632-4673 fax: 632-1228
http://stat.ethz.ch/~buser/
--------------------------------------------------------------
Philippe Lamy writes:
> Hi,
>
> I have a model with differents observations Xi.
> Each observation belongs to a group, either A or B.
> I would like to minimize a fonction like :
>
> sum( Xi - Z)^2 + sum (Xi - aZ -b)^2
> A B
>
> The first sum contains all observations from group A and the second all
> observations from group B.
> I want to find the Z-value wich minimize this function. a and b are predefined
> parameters.
>
> Thanks for help.
>
> Philippe
>
> ______________________________________________
>
More information about the R-help
mailing list