4

ある年がうるう年かどうかを計算する関数を作成しました。次のようになります。

isLeapday<-function(x) {
     if (as.numeric(x)%%100==0 & as.numeric(x)%%400==0 | as.numeric(x)%%4==0 &      as.numeric(x)%%100!=0) return (TRUE) 
     else return (FALSE)
}


isLeapday(x)

エラーメッセージが表示されます

"In if(as.numeric(x)%% 100 == 0&as.numeric(x)%% 400 == 0 | as.numeric(x)%% 4 ==:条件の長さは>1でのみ最初の要素が使用されます」

基本的に最初の値のみが計算されますが、ベクトル内のすべての値をカウントし、可能であれば論理ベクトルを返すようにするにはどうすればよいですか?

4

1 に答える 1

6
isLeapday<-function(x) {
  x %% 100 == 0 & x %% 400 == 0 | x %% 4 == 0 & x %% 100 != 0
}

years <- 2004:2013

isLeapday(years)

# [1]  TRUE FALSE FALSE FALSE  TRUE FALSE FALSE FALSE  TRUE FALSE

またはmnelが述べたように:

library("chron")
leap.year(years)

 [1]  TRUE FALSE FALSE FALSE  TRUE FALSE FALSE FALSE  TRUE FALSE

のコードについてleap.year{chron}

library("chron") 
edit(leap.year)

function (y) 
{
    if (inherits(y, "dates")) 
        y <- month.day.year(as.numeric(y), origin. = origin(y))$year
    y%%4 == 0 & (y%%100 != 0 | y%%400 == 0)
}
于 2013-02-20T22:40:57.853 に答える