[R] Getting an error calling MASS::boxcox in a function

Bert Gunter
Sat, 08 Jul 2023 15:28:21 -0000

Try this for your function:

BoxCoxLambda <- function(z){
   y <- z
   b <- boxcox(y + 1 ~ 1,lambda = seq(-5, 5, length.out = 61), plotit FALSE)
   b$x[which.max(b$y)]    # best lambda
}

***I think*** (corrections and clarification strongly welcomed!) that `~`
(the formula function) is looking for 'z' in the GlobalEnv, the caller
of
apply(), and not finding it. It finds 'y' here explicitly in the
BoxCoxLambda environment.

Cheers,
Bert



On Sat, Jul 8, 2023 at 4:28?AM Ron Crump via R-help <r-help at
r-project.org>
wrote:

> Hi,
>
> Firstly, apologies as I have posted this on community.rstudio.com too.
>
> I want to optimise a Box-Cox transformation on columns of a matrix (ie, a
> unique lambda for each column). So I wrote a function that includes the
> call to MASS::boxcox in order that it can be applied to each column easily.
> Except that I'm getting an error when calling the function. If I just
> extract a column of the matrix and run the code not in the function, it
> works. If I call the function either with an extracted column (ie dd1 in
> the reprex below) or in a call to apply I get an error (see the reprex
> below).
>
> I'm sure I'm doing something silly, but I can't see what it is.
Any help
> appreciated.
>
> library(MASS)
>
> # Find optimised Lambda for Boc-Cox transformation
> BoxCoxLambda <- function(z){
>     b <- boxcox(lm(z+1 ~ 1), lambda = seq(-5, 5, length.out = 61),
plotit
> = FALSE)
>     b$x[which.max(b$y)]    # best lambda
> }
>
> mrow <- 500
> mcol <- 2
> set.seed(12345)
> dd <- matrix(rgamma(mrow*mcol, shape = 2, scale = 5), nrow = mrow, ncol
> mcol)
>
> # Try it not using the BoxCoxLambda function:
> dd1 <- dd[,1] # 1st column of dd
> bb <- boxcox(lm(dd1+1 ~ 1), lambda = seq(-5, 5, length.out = 101),
plotit
> = FALSE)
> print(paste0("1st column's lambda is ",
bb$x[which.max(bb$y)]))
> #> [1] "1st column's lambda is 0.2"
>
> # Calculate lambda for each column of dd
> lambdas <- apply(dd, 2, BoxCoxLambda, simplify = TRUE)
> #> Error in eval(predvars, data, env): object 'z' not found
>
> Created on 2023-07-08 with reprex v2.0.2
>
> Thanks for your time and help.
>
> Ron
>         [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
> 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.
>

	[[alternative HTML version deleted]]