[R] implementing a "loop" using by(x,x$factor,FUN)
Mohamed Abdolell
m.abdolell at utoronto.ca
Fri Nov 19 00:14:56 CET 2004
Hi,
I'm writing some R code that requires a massive amount of looping and would
ideally like to write it so that it avoid the use of "for" loop ... however I'm
having some trouble.
Very briefly, the basic idea is to implement a binary partitioning algorithm to
determine the optimal cutpoint based on deviance measures obtained from
likelihood estiamtes. This is in the geo-spatial context so I'm actually using
the geoRglm package to obtain this likelihood fit. I initially use the "variog"
function to help specify the initial parameter values passed to "likfit" to
ensure convergence.
Although not the most elegant solution, the code works ... I just want to
re-code it to avoid using the "for" loop.
Any help would be greatly appreciated.
This is what I've got ....
RootDev <- 600
splits <- NULL
for (cutpoint in cutpoints) {
LRGdata <- split(gdata, gdata[,4] <= cutpoint)
vgrmL <- variog(as.geodata(LRGdata$"TRUE"), covar.col=covcol))
vgrmR <- variog(as.geodata(LRGdata$"FALSE"), covar.col=covcol))
mlL<- likfit(as.geodata(LRGdata$"TRUE"),
ini=expand.grid(seq(0, max(vgrmL$v), l=10), seq(0,max(vgrmL$u), l=10)))
mlR<- likfit(as.geodata(LRGdata$"FALSE"),
ini=expand.grid(seq(0, max(vgrmR$v), l=10), seq(0,max(vgrmR$u), l=10)))
LeftDev <- summary(mlL)[[8]]$log.L
RightDev <- summary(mlR)[[8]]$log.L
LeftN <- dim(LRGdata$"TRUE")[1]
RightN <- dim(LRGdata$"FALSE")[1]
splits <- rbind(splits, c(paste("<=",cutpoint),paste(">",cutpoint),
LeftN, RightN, RootDev, LeftDev, RightDev,
-2*(RootDev-(LeftDev+RightDev))))
}
- Mohamed
More information about the R-help
mailing list