Compute each value in a vector inside a function

I made a function that will calculate if a certain year is a jump that looks like this:

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) 

I get an error

"In if (as.numeric (x) %% 100 == 0 and as.numeric (x) %% 400 == 0 | as.numeric (x) %% 4 ==: the condition has a length> 1, and will be only the first element is used "

Basically, only the first value is calculated, how can I make it so that it takes into account each value inside the vector and, if possible, returns a logical vector?

+4
source share
1 answer
 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 

Or as mentioned in mnel:

 library("chron") leap.year(years) [1] TRUE FALSE FALSE FALSE TRUE FALSE FALSE FALSE TRUE FALSE 

For leap.year{chron} code 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) } 
+6
source

All Articles