Reputation: 133
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")
Upvotes: 2
Views: 1153
Reputation: 56024
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
Upvotes: 4