0

Working to eventually put an exponential fit on some data, but running into errors with the datatype of a Date object. How can I convert a vector of dates into a format that can be read by the exp() function? Largely, I am trying to make this example work for me, but get error:

Error in Math.Date(date) : exp not defined for "Date" objects

I have tried converting using as.numeric(), but get error

 Error in lm.fit(x, y, offset = offset, singular.ok = singular.ok, ...) : 
  NA/NaN/Inf in 'x'

Converting the date object to a smaller number (ie days from first date, weeks from first date) solved the issue. Below is updated code to make the example work:

weight <- c(1000, 100, 10, 1)
date <- as.Date(c('2010-11-1','2010-3-25','2010-2-2','2010-1-14'))
df <- data.frame(date, weight)

df$doy_str <- strftime(df$date, format = "%j")
df$doy <- as.numeric(df$doy_str)


linear.model <-lm(weight ~ doy, df)
log.model <-lm(log(weight) ~ doy, df)
exp.model <-lm(weight ~ exp(doy), df)

log.model.df <- data.frame(x = df$doy,
                           y = exp(fitted(log.model)))

ggplot(df, aes(x=doy, y=weight)) + 
  geom_point() +
  geom_smooth(method="lm", aes(color="Exp Model"), formula= (y ~ exp(x)), se=FALSE, linetype = 1) +
  geom_line(data = log.model.df, aes(x,y, color = "Log Model"), size = 1, linetype = 2) + 
  guides(color = guide_legend("Model Type"))
cj19011
  • 5
  • 2
  • Perhaps `exp(c(0, diff(date)))`? It depends on the login behind your real data and analysis. – r2evans Nov 26 '19 at 00:39
  • Are `log(weight)~date` and `weight~exp(date)` similar enough? Or is that what you're trying to verify/validate? – r2evans Nov 26 '19 at 15:47

1 Answers1

0

I think the issue, even with numeric is that dates convert to days from 1970-01-01. Putting a number that large into exp will return infinity. You could first convert your date to days from a more recent origin (eg. your minimum date in the data)

SmokeyShakers
  • 2,075
  • 1
  • 5
  • 12
  • This is helpful! I think this will solve my problem. I converted my date to days from my minimum date in the data, but I get error `Warning message: Computation failed in `stat_smooth()`: NA/NaN/Inf in 'x' ` when I add the model to a ggplot. I have updated by question to reflect this. – cj19011 Nov 27 '19 at 16:22
  • Hmm, I'd check what numeric values your 'days from minimum' are. Any thing over 710 and exp will return Inf, which will be a problem. If that's the case, you could scale further (eg. weeks or months) – SmokeyShakers Nov 27 '19 at 16:30
  • Discovered my problem, forgot to update my date variable in a line! Converting to days to reduce the number solved the problem, thanks SmokeyShakers ! – cj19011 Nov 27 '19 at 16:45