# Error in boxcox.default(y ~ x) : response variable must be positive

Error in boxcox.default(y ~ x) : response variable must be positive


I am getting this error in R when I am performing a Box-Cox transformation on data.

Why is this error happening? Here is my data.

This is a time series data and I have to perform logarithmic regression of the form:

$$y=a+b(\log x_1)+c(\log x_2)$$

I need to find a, b, c and then, check if any such type of relation exists or not.

• As the error message says, you're getting this error because there are negative values in your response vector $y$. When the Box-Cox procedure determines which transformation to use, it uses the geometric mean $(y_1\cdot y_2\cdots y_n)^{1/n}$ in the computation. The geometric mean is only defined when all $y_i$ are positive, as taking roots of negative numbers may lead to imaginary/complex numbers. Therefore all $y_i$ must be positive in order to use Box-Cox. – MånsT Jan 9 '13 at 9:49
• You might want to look into the related Yeo-Johnson transformation within the boxCox function in the package car, and the yjpower function in the same package – Glen_b Feb 15 '14 at 7:49

Yes, the boxcox only works with positive values for the response variable $Y$. More details can be found in wikipedia. To workaround this limitation, you can try to predict a shifted version $Y+\mu$ (with $\mu \gt \min Y$) of your variable instead.

A quick code example:

library(MASS)

## Invent example for x and y
y = c(rnorm(100,3,300), rnorm(30,1600,400))
x = 1:length(y)
## Histogram of y shows that y is skewed
hist(y)
## Define parameters for boxcox
eps = 1e-5
n = 100;
mu = seq(-min(y) + eps, max(y), length = n)
lambda = seq(0, 5, length = n)
## Initialize then calculate log likelihood values
lik = matrix(0, n, n)
for (i in 1:n) lik[, i] = boxcox((y + mu[i])~x, lambda = lambda, plotit = FALSE)$y ## Plot log likelihood values image(lik, xlab = "mu", ylab = "lambda", main = "likelihood")  • Thank you ..I will try it..Is the result equivalent to log transformation ? Can you give any link or explanation with sample data.It would be of great help :))) – Komal Jan 9 '13 at 11:52 •$\lambda = \mu = 0$will be equivalent to a log transformation but in the general case, it is going to be different. You can try to run the example with any vector$y$and$x\$ that have the same size. – ThePawn Jan 10 '13 at 0:12
• Sample data file link : LINK FOR DATA FILE ON WHICH I WANT TO PERFORM THE OPERATION.This is time series data and i have to perform logarithmic regression of form y=a+b(logx1)+c(logx2). and find a,b,c and then check is there any such type of relation exists or not. – Komal Jan 11 '13 at 5:35