[R] for loop not working in function

Prof Brian Ripley ripley at stats.ox.ac.uk
Wed Oct 11 09:52:03 CEST 2006


On Wed, 11 Oct 2006, Dale Steele wrote:

> I'm trying to write a small function (below) to compute Box & Cox
> transformations of x for arbitrary values of lambda.

It seems to compute the log-likihoods of transformed models.

> I'd like to
> specify a range of values for lamba (min,max,step) and am having trouble
> getting the for loop to work.  Suggestions?

The body of a for loop needs to be enclosed in braces.  An indenting 
editor will help a lot, e.g. ESS gave

boxcox <- function(x,min,max,step)
{
     lambda <- seq(min,max,step)
     s <- length(lambda)
     for (lambda in 1:s)
         n <- nrow(x)
     if(lambda ==0) xL <- log(x) else
     xL <- ((x^lambda) - 1)/lambda
     xLbar <- mean(xL)
     t1 <- (-n/2)* log((1/n)*sum((xL -  xLbar)^2))
     t2 <- (lambda - 1)*sum(log(x))
     l= t1 + t2
     l
}

Here is a better version:

boxcox <- function(x, min, max, step)
{
     all_lambda <- seq(min, max, step)
     n <- length(x)
     res <- numeric(length(all_lambda))
     for (i in seq(along=all_lambda)) {
         lambda <- all_lambda[i]
         xL <- if(lambda == 0) log(x) else ((x^lambda) - 1)/lambda
         xLbar <- mean(xL)
         t1 <- (-n/2)* log((1/n)*sum((xL -  xLbar)^2))
         t2 <- (lambda - 1)*sum(log(x))
         res[i] <- t1 + t2
     }
     names(res) <- all_lambda
     res
}


> Any pointers to resources for learning to write functions in R for
> neophyte programmers?  Thanks.  --Dale

'An Introduction to R', in the first instance.

>
>
> boxcox <- function(x,min,max,step) {
> lambda <- seq(min,max,step)
> s <- length(lambda)
> for (lambda in 1:s)
> n <- nrow(x)
> if(lambda ==0) xL <- log(x) else
> xL <- ((x^lambda) - 1)/lambda
> xLbar <- mean(xL)
> t1 <- (-n/2)* log((1/n)*sum((xL -  xLbar)^2))
> t2 <- (lambda - 1)*sum(log(x))
> l= t1 + t2
> l
> }
>
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>

-- 
Brian D. Ripley,                  ripley at stats.ox.ac.uk
Professor of Applied Statistics,  http://www.stats.ox.ac.uk/~ripley/
University of Oxford,             Tel:  +44 1865 272861 (self)
1 South Parks Road,                     +44 1865 272866 (PA)
Oxford OX1 3TG, UK                Fax:  +44 1865 272595



More information about the R-help mailing list