日期相减
与数值一样,日期也可以进行算术运算。特别是,您可以通过相减来计算两个日期之间相差的天数:
today <- as.Date("2017-01-02")
tomorrow <- as.Date("2017-01-03")
one_year_away <- as.Date("2018-01-02")
tomorrow - today
Time difference of 1 days
one_year_away - today
Time difference of 365 days
同样,您也可以使用 difftime() 函数来计算时间间隔。
difftime(tomorrow, today)
Time difference of 1 days
# 还可以添加一些额外选项!
difftime(tomorrow, today, units = "secs")
Time difference of 86400 secs
本练习是课程的一部分
R 金融中级
练习说明
- 我们已为您创建了一个
dates向量。 - 您可以通过相减来验证 R 计数的起始日期为 1970 年 1 月 1 日。首先,创建一个名为
origin的变量,其中包含将"1970-01-01"转换为日期后的值。 - 现在,对
dates使用as.numeric(),查看自 1970 年 1 月 1 日以来已经过了多少天。 - 最后,用
dates减去origin来验证结果!(留意这里使用了回收规则!)
交互式实操练习
通过完成这段示例代码来试试这个练习。
# Dates
dates <- as.Date(c("2017-01-01", "2017-01-02", "2017-01-03"))
# Create the origin
origin <- ___
# Use as.numeric() on dates
___
# Find the difference between dates and origin
___