[英]Calculate every value in a vector within a function
I made a function which will calculate if a certain year is a leapyear which looks like this: 我制作了一个函数,该函数将计算某个年份是否为a年,如下所示:
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 the error message 我收到错误消息
"In if (as.numeric(x)%%100 == 0 & as.numeric(x)%%400 == 0 | as.numeric(x)%%4 == : the condition has length > 1 and only the first element will be used"“如果((as.numeric(x)%% 100 == 0&as.numeric(x)%% 400 == 0 | as.numeric(x)%% 4 ==:条件的长度> 1并且仅将使用第一个元素”
Basically only the first value is calculated, how do I make it so that it counts every value within the vector and if possible, returns a logical vector? 基本上只计算第一个值,如何使它计算向量中的每个值,并在可能的情况下返回逻辑向量?
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 mnel mentioned: 或如mnel所述:
library("chron")
leap.year(years)
[1] TRUE FALSE FALSE FALSE TRUE FALSE FALSE FALSE TRUE FALSE
For the code of leap.year{chron}
: 对于
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)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.