数学建模社区-数学中国
标题:
怎样用function来检验是否是闰年
[打印本页]
作者:
夜筱巫
时间:
2013-8-1 06:07
标题:
怎样用function来检验是否是闰年
我要写个function来检验末年是否是闰年。开头这样:
leapyear<-function(x){}
复制代码
闰年这里的定义是:
9 _8 x$ J# m3 U" {3 T1 `
如果那一年可以整除4(比如2004),2月就有29天
8 L& d w& `5 J* F7 {1 _
如果那一年不能整除100
) P. _3 r( Z: q# V$ B$ A g2 b
如果那一年可以整除400
: o3 ~0 V2 U: e( [: {' ^
1 X% M* l' A- }# U2 Y
如果x<1,这个function就要return “error”。我不大懂这个条件的意思,可否请大师解释下?
) O% `" q; ]' j7 e1 V, w
" d% M, C3 w: i/ H' X
我写的function是这样的:
leapyear<- function(dates, years_to_add)
4 q/ k, l/ E, {, ~6 g
{
9 K0 R0 a$ |. N$ E) b3 X
if(!require(lubridate)) stop("install lubridate")
$ V& e6 c: P7 P4 o5 Y) p5 b
if(years_to_add > floor(years_to_add)) stop("error")
% A2 e1 o0 e# p
$ X2 b4 D; n1 h: R/ p: l( w
new <- dates + years(years_to_add)
7 l- m: I& r6 Y3 f" ?2 ^
new[
^6 q! \* {2 d, p% _
leap_year(year(dates)) &
; }. u' x. x0 L
!leap_year(year(dates) + years_to_add) &
/ Z) C4 c/ [2 k0 t9 p( y
month(dates) == 2 &
, G7 ~* N4 C# C2 Q8 ?# G! ~" v9 l3 M
day(dates) == 29
9 W, Q4 S6 y/ Z- b* ]: t
] <- NA
* y8 d( w8 F5 \: x0 l8 s: s
new_dates
/ e" ~. _1 h/ V2 ~/ a+ o
}
$ f) x' O2 |& N
; g9 v# U# T. |1 n6 Q K3 Y
dates <- ymd(c("2004-2-28", "2004-2-29"))
复制代码
不知道对不对,但是检验的时候显示ymd找不到。。。。
/ W4 d4 H& G2 |7 z+ i* S, b; U
& p. X: \6 |5 G1 p
请各位大师帮帮忙!小妹感激不尽!
欢迎光临 数学建模社区-数学中国 (http://www.madio.net/)
Powered by Discuz! X2.5