2

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
MattB
  • 651
  • 3
  • 11

2 Answers2

4

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
MattB
  • 651
  • 3
  • 11
  • See my answer. I believe you should include its code in your answer. It does nothing more than to rewrite your code as a function. – Rui Barradas Jun 17 '20 at 18:07
1

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
halfer
  • 19,824
  • 17
  • 99
  • 186
Rui Barradas
  • 70,273
  • 8
  • 34
  • 66