我制作了一个函数,用于计算某一年是否是一个看起来像这样的年级:
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)
我收到错误消息
“在if(as.numeric(x)%% 100 == 0&amp; as.numeric(x)%% 400 == 0 | as.numeric( x)%% 4 ==: 条件的长度> 1,只使用第一个元素“
基本上只计算第一个值,如何计算它以便计算向量中的每个值,如果可能,返回逻辑向量?
答案 0 :(得分: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)
}