2
votes

I want to calculate the number of months between two dates but before that I have a problem when loading the data in r. In csv sheet the format is mm/dd/yyyy but in R the variable is classified as character.

I tried

data$issue_d <- format(as.Date(data$issue_d), "%m/%d/%Y")

and to convert as date first but it gives the following error

character string is not in a standard unambiguous format

Any suggestion for this?

Example input:

issue_d <- c("Dec,2011","Nov,2014","Apr,2015") 
1
Looks like a typo... try: data$issue_d <- as.Date(data$issue_d, format = "%m/%d/%Y")zx8754
Related post, where error is explained: stackoverflow.com/questions/14755425/…zx8754
@zx8754 it gives all NAErick
Change the format argument.zx8754
Date class also need day and that is the issue with the codeakrun

1 Answers

4
votes

Try below:

# example data
df1 <- data.frame(
  issue_d1 = c("Dec,2011","Nov,2014","Apr,2015"),
  issue_d2 = c("Nov,2015","Sep,2017","Apr,2018"))


library(zoo)

df1$Months <- 
  (as.yearmon(df1$issue_d2, "%b,%Y") - 
     as.yearmon(df1$issue_d1, "%b,%Y")) * 12

df1
#   issue_d1 issue_d2 Months
# 1 Dec,2011 Nov,2015     47
# 2 Nov,2014 Sep,2017     34
# 3 Apr,2015 Apr,2018     36