Is there an R equivalent to Excel's LOGEST function?

Viewed 272

I need to exactly replicate Excel's LOGEST function in R, but can't find a way of doing it without using generic least squares estimation. Before I write some custom code myself, has anyone come across such a thing?

data <- 2:7

Desired output (from Excel's LOGEST function):

1.27730742  1.758076359
2 Answers

Just log the data, do a linear regression, then exp the results.

result <- lm(log(data) ~ seq_along(data))
exp(result$coefficients)

(I would have found this earlier but I was getting loge and log10 confused like a fool.)

EDIT: @Rui Barradas has kindly made this into a function: here it is:

logest <- function(y, x, ...){
  if(missing(x) || is.null(x)) x <- seq_along(y)
  result <- lm(log(y) ~ x, ...)
  exp(coef(result))
}

data <- 2:7
logest(data)
#(Intercept)           x 
#   1.758076    1.277307

This answer is entirely based in the answer by user @MattB.

logest <- function(y, x, ...){
  if(missing(x) || is.null(x)) x <- seq_along(y)
  result <- lm(log(y) ~ x, ...)
  exp(coef(result))
}

data <- 2:7
logest(data)
#(Intercept)           x 
#   1.758076    1.277307

This second example uses the example data in the question link. The results are equal to the results posted there.

x <- 11:16
y <- c(33100, 47300, 69000, 102000, 150000, 220000)
logest(y, x)
#(Intercept)           x 
# 495.304770    1.463276
Related