我想计算两个日期之间的月数,但在此之前我在r中加载数据时遇到问题。在csv表格中,格式为mm/dd/yyyy
,但在R中,变量被归类为字符。
我试过
data$issue_d <- format(as.Date(data$issue_d), "%m/%d/%Y")
并首先转换为日期,但它会出现以下错误
字符串不是标准的明确格式
对此有何建议?
示例输入:
issue_d <- c("Dec,2011","Nov,2014","Apr,2015")
答案 0 :(得分:4)
尝试以下:
# 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