数学建模社区-数学中国

标题: 怎样用function来检验是否是闰年 [打印本页]

作者: 夜筱巫    时间: 2013-8-1 06:07
标题: 怎样用function来检验是否是闰年
我要写个function来检验末年是否是闰年。开头这样:
  1. 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是这样的:
  1. leapyear<- function(dates, years_to_add)
    4 q/ k, l/ E, {, ~6 g
  2. {
    9 K0 R0 a$ |. N$ E) b3 X
  3.   if(!require(lubridate)) stop("install lubridate")
    $ V& e6 c: P7 P4 o5 Y) p5 b
  4.   if(years_to_add > floor(years_to_add)) stop("error")% A2 e1 o0 e# p
  5.   $ X2 b4 D; n1 h: R/ p: l( w
  6.   new <- dates + years(years_to_add)7 l- m: I& r6 Y3 f" ?2 ^
  7.   new[  ^6 q! \* {2 d, p% _
  8.     leap_year(year(dates)) &
    ; }. u' x. x0 L
  9.       !leap_year(year(dates) + years_to_add) &
    / Z) C4 c/ [2 k0 t9 p( y
  10.       month(dates) == 2 &
    , G7 ~* N4 C# C2 Q8 ?# G! ~" v9 l3 M
  11.       day(dates) == 299 W, Q4 S6 y/ Z- b* ]: t
  12.     ] <- NA
    * y8 d( w8 F5 \: x0 l8 s: s
  13.   new_dates
    / e" ~. _1 h/ V2 ~/ a+ o
  14. }
    $ f) x' O2 |& N

  15. ; g9 v# U# T. |1 n6 Q  K3 Y
  16. 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