计算函数内向量中的每个值

Per*_*son 4 r function vector

我做了一个函数,它将计算某一年是否是一个如此的leapyear:

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)
Run Code Online (Sandbox Code Playgroud)

我收到错误消息

"在if(as.numeric(x)%% 100 == 0&as.numeric(x)%% 400 == 0 | as.numeric(x)%% 4 ==:条件长度> 1且仅将使用第一个元素"

基本上只计算第一个值,如何使它计算向量中的每个值,如果可能,返回逻辑向量?

N8T*_*TRO 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
Run Code Online (Sandbox Code Playgroud)

或者正如mnel所说:

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

 [1]  TRUE FALSE FALSE FALSE  TRUE FALSE FALSE FALSE  TRUE FALSE
Run Code Online (Sandbox Code Playgroud)

对于代码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)
}
Run Code Online (Sandbox Code Playgroud)