【发布时间】:2016-06-14 19:17:55
【问题描述】:
所以我想将“2010 年 10 月”和“2010 年 11 月”转换为数字格式,因此如果我取这两者的差值,我会得到结果:1。
我尝试使用 as.date 函数,但它似乎只适用于完整格式:月-日-年。
【问题讨论】:
-
我尝试使用命令:as.Date(as.yearmon(x)) 但它默认给我日期,我怎样才能只保留月份和年份?
所以我想将“2010 年 10 月”和“2010 年 11 月”转换为数字格式,因此如果我取这两者的差值,我会得到结果:1。
我尝试使用 as.date 函数,但它似乎只适用于完整格式:月-日-年。
【问题讨论】:
您可以尝试格式化原始日期字符串,并将每个字符串视为该月的第一天。
dates <- c("October 2010", "November 2010")
# extract the first three letters for the month, and the last 4 digits for the year
dates.new <- paste0(substr(dates, 1, 3), "-01-", substr(dates, nchar(dates)-3, nchar(dates)))
> dates.new
[1] "Oct-01-2010" "Nov-01-2010"
# convert to POSIXct
dates.posix <- as.POSIXct(dates.new, format="%B-%d-%y")
diff <- dates.posix[2] - dates.posix[1]
> diff
Time difference of 31 days
【讨论】:
在您的问题中,您想计算月数而不是天数的差异。您可以将 month-year 字符向量映射到数字月数,从数据集中第一个月的第 1 个月开始,到数据集中最后一个月的第 n 个月结束。那么计算月数的差异就很简单了。
或者 - 为了能够操作日期时间对象 - 您必须创建完整日期,方法是在所有日期前引入 01,例如“2010 年 11 月 1 日”,然后计算日期之间的差异。这是下面答案的主要部分。
lubridate 包可以计算两个日期之间的差异。它处理诸如 2 月 29 日这样的重要问题。如果您的系统上没有安装它:
install.packages("lubridate")
然后
library(lubridate)
ymd("20160301")-ymd("20160228")
# Time difference of 2 days
ymd("20150301")-ymd("20150228")
# Time difference of 1 days
要阅读完整的月份名称,请查看 help(parse_date_time) 中的格式详细信息
d <- parse_date_time("November 01 2010", "Bdy") - parse_date_time("October 01 2010", "Bdy")
d
# Time difference of 31 days
d 是一个difftime 对象,(基于converting a difftime to integer)您可以将其转换为天数和周数(但不能转换为月数):
class(d)
# [1] "difftime"
as.numeric(d, units="days")
# [1] 31
as.numeric(d, units="weeks")
# [1] 4.428571
【讨论】: