LoginSignup
0
0

More than 1 year has passed since last update.

R で閏年判定

Posted at

1. tis パッケージを使う。

> library(tis)
> isLeapYear(c(2020, 2022, 2100, 2400))
[1]  TRUE FALSE FALSE  TRUE

isLeapYear は以下の関数定義

isLeapYear <- function (y) 
{
    y%%4 == 0 & (y%%100 != 0 | y%%400 == 0)
}

2. lubridate パッケージを使う。

> library(lubridate)
> leap_year(c(2020, 2022, 2100, 2400))
[1]  TRUE FALSE FALSE  TRUE

引数に Date オブジェクトも使える
> leap_year(as.Date(c("2020-09-29", "2022-09-19", "2100-09-19", "2400-09-19")))
[1]  TRUE FALSE FALSE  TRUE

leap_year は以下の関数定義

leap_year <- function (date) 
{
    if (is.numeric(date)) {
        year <- date
    }
    else {
        year <- year(date)
    }
    (year%%4 == 0) & ((year%%100 != 0) | (year%%400 == 0))
}

3. 結論

他にもあるかもしれないが,基本は y%%4 == 0 & (y%%100 != 0 | y%%400 == 0)

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0