0

I am using a dataset to calculate the growth in earnings from 2000-2019 and have the earnings for every month within those years. It is in the ymd format, eg 2000-01-01

I am trying to calculate the growth rate between each month but it won't let me use the lag function properly due to the year column being in date format as above.

Code is:

average_weekly_earnings <- average_weekly_earnings %>% 
  group_by(year) %>% 
  mutate(diff_earnings_average = year - lag(year),
         diff_aveearnings_growth = realawe - lag(realawe),
         rate_percent_average = (diff_aveearnings_growth/diff_earnings_average)/realawe*100)

Error in /.difftime(diff_aveearnings_growth,diff_earninigs_average: second argument of /cannot be a 'difftime'object This code appears when I try to run it.

Does anyone known how to fix this?

This is the dput output:

structure(list(year = structure(c(946684800, 949363200, 951868800, 
954547200), class = c("POSIXct", "POSIXt"), tzone = "UTC"), realawe = c(421.168268440558, 
410.160453374782, 422.012733947076, 423.306583956499), diff_aveearnings_growth = c(NA, 
-11.0078150657755, 11.8522805722941, 1.29385000942239), rate_percent_average = c(NA, 
-2.68378264535347, 2.80851254450074, 0.305653173954731)), class = c("tbl_df", 
"tbl", "data.frame"), row.names = c(NA, -4L))
StupidWolf
  • 45,075
  • 17
  • 40
  • 72
josh
  • 73
  • 1
  • 5
  • 3
    Hi josh, it will be much easier to help if you provide at least a sample of your data with `dput(average_weekly_earnings)` or if your data is very large `dput([average_weekly_earnings 1:40,])`. You can edit your question and paste the output. You can surround it with three backticks (```) for better formatting. See [How to make a reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) for more info. – Ian Campbell Apr 29 '20 at 15:02
  • 1
    you can create another year column using year() from lubridate, not very sure what you are trying to calculate, so maybe your take it from there – StupidWolf Apr 29 '20 at 19:34
  • 2
    try using `as.numeric(diff_earnings_average)` in your denominator in calculating `rate_percent_average` - perhaps the problem is diving one `difftime` by another `difftime` - see this [related question](https://stackoverflow.com/questions/40227472/divide-two-difftime-objects). – Ben Apr 29 '20 at 19:51

0 Answers0