區間

在 R 中處理日期與時間

Charlotte Wickham

Instructor

建立區間

datetime1 %--% datetime2,或
interval(datetime1, datetime2)

dmy("5 January 1961") %--% dmy("30 January 1969")
1961-01-05 UTC--1969-01-30 UTC
interval(dmy("5 January 1961"), dmy("30 January 1969"))
1961-01-05 UTC--1969-01-30 UTC
在 R 中處理日期與時間

操作區間

beatles <- dmy("5 January 1961") %--% dmy("30 January 1969")

int_start(beatles)
"1961-01-05 UTC"
int_end(beatles)
"1969-01-30 UTC"
在 R 中處理日期與時間

操作區間

int_length(beatles)
254620800
as.period(beatles)
"8y 0m 25d 0H 0M 0S"
as.duration(beatles)
"254620800s (~8.07 years)"
在 R 中處理日期與時間

比較區間

hendrix_at_woodstock <- mdy("August 17 1969")
hendrix_at_woodstock %within% beatles
FALSE
hendrix <- dmy("01 October 1966") %--% dmy("16 September 1970")
int_overlaps(beatles, hendrix)
TRUE
在 R 中處理日期與時間

選哪種時間跨度?

使用:

  • 有「開始」與「結束」時用 Intervals
  • 關心人類時間單位時用 Periods
  • 只在意經過秒數時用 Durations
在 R 中處理日期與時間

英格蘭君主

英國君主

monarchs
# A tibble: 131 x 4
                              name       from         to       dominion
                             <chr>     <dttm>     <dttm>          <chr>
 1                    Elizabeth II 1952-02-06 2017-10-07 United Kingdom
 2                        Victoria 1837-06-20 1901-01-22 United Kingdom
 3                        George V 1910-05-06 1936-01-20 United Kingdom
 4                      George III 1801-01-01 1820-01-29 United Kingdom
# ... with 127 more rows
在 R 中處理日期與時間

哈雷彗星

哈雷彗星: https://en.wikipedia.org/wiki/Halley%27s_Comet#Apparitions

halleys
# A tibble: 27 x 6
      designation  year perihelion_date start_date   end_date distance
            <chr> <int>          <date>     <date>     <date>    <chr>
 1   1P/66 B1, 66    66      0066-01-26 0066-01-25 0066-01-26     <NA>
 2 1P/141 F1, 141   141      0141-03-25 0141-03-22 0141-03-25     <NA>
 3 1P/218 H1, 218   218      0218-04-06 0218-04-06 0218-05-17     <NA>
 4 1P/295 J1, 295   295      0295-04-07 0295-04-07 0295-04-20     <NA>
# ... with 23 more rows
在 R 中處理日期與時間

一起來練習吧!

在 R 中處理日期與時間

Preparing Video For Download...