0

I am trying to calculate the month difference between year month dates. For example in the dataframe I have the following year/months and I would like to calculate the following results:-

Year/Month Result 201910 N/a 201912 2 202001 1 202010 9

So it calculates the difference from the current row Year/Month from the previous row.So I was thinking something like df$result <- df$Year/Month-lag(df$Year/Month)

However, this won't work for 202001-201912. I know there is a function DATEDIF in excel which works if you have full dates ie. 01/12/2019 - 01/01/2020 =DATEDIF(A1,A2,"M"). I am hoping I can find a solution in r. Any information that may point me in the right direction would be appreciated. I appreciate, I might be being a bit vague but I am relatively new to this.

Cheers,

Forrestgump1980

James Elwell
  • 11
  • 1
  • 2
  • https://stat.ethz.ch/R-manual/R-devel/library/base/html/difftime.html – dk14 Mar 04 '20 at 08:38
  • 2
    Does this answer your question? [Get the difference between dates in terms of weeks, months, quarters, and years](https://stackoverflow.com/questions/14454476/get-the-difference-between-dates-in-terms-of-weeks-months-quarters-and-years) – dk14 Mar 04 '20 at 08:40
  • Thanks for these articles dk14 these are definitely on the right lines. The only strange thing is I have installed zoo 'install.packages("zoo")' but when I try and use as.yearmon I am getting an error messgae 'Error in as.yearmon("2007-12") : could not find function "as.yearmon"' – James Elwell Mar 04 '20 at 09:01
  • did you do `library(zoo)` before as.yearmon? – dk14 Mar 04 '20 at 09:10
  • good point i didn't – James Elwell Mar 04 '20 at 09:12
  • ok its working now. Let me try a few things to see if I can figure it out. – James Elwell Mar 04 '20 at 09:13
  • I am just having an issue setting the 'Year/Month' column to be recognized as a date. It is currently set to numeric. I am trying 'as.POSIXct(Conversion$`Year/Month`,origin = "%Y-%M")' but I get the error 'character string is not in a standard unambiguous format'. – James Elwell Mar 04 '20 at 09:39
  • I managed to work this out from the links attached. Thanks for your help. – James Elwell Mar 04 '20 at 15:29

0 Answers0