4.2 Date-time components

This section will focus on the accessor functions that let you get and set individual components of a date / datetime.

4.2.1 Accessing components

To pull out individual parts of the date with the accessor functions, use: year(), month(), mday()(day of month), yday()(day of year), wday()(day of week), hour(), minute(), second()

For month() and wday() you can set label = TRUE to return the abbreviated name of the month or day of the week and convert it to a factor. Set abbr = FALSE to return the full name. This is useful when plotting in ggplot2 because you want a certain order

通过 wday()函数,我们可以知道在工作日出发的航班要多于周末出发的航班:

再看一个使用 minute() 函数获取分钟成分的例子。比如我们想知道出发时间的分钟数与平均到达延误时间的关系:

我们可以发现一个有趣的趋势,似乎在 20 ~ 30 分钟和第 50 ~ 60 分钟出发的航班的到达延误时间远远低于其他时间出发的航班。

4.2.3 Setting components

You can also use each accessor function to set the components of a date/time::

Alternatively, rather than modifying in place, you can create a new date-time with update(). This also allows you to set multiple values at once, the api is similar to make_datetime().

如果修改yday,相当于同时修改 mdaymonth:

If values are too big, they will roll-over:

update() 函数还有一种比较巧妙的用法,比如我们想可视化一年中所有航班的的出发时间在一天中的分布:

如果不用 update() ,我们可能需要先用hour()、minute()、second()获取三种成分,然后再用make_datetime()对这三种成分进行合并。