2016-07-31 70 views
0

Lubridateパッケージを使用すると、うるう年を考慮して、2回の間の数値の年齢をどのように決定できますか。R rubridate、うるう年を含む年齢の計算

年齢が「ミリ秒」、「秒」、「分」、「週」、「月」、「年」などのさまざまな単位で指定される関数を必要とします。 。

age <- function(from, to = today(), units = "years", floor = FALSE) { 
    calc = interval(from,to)/duration(num = 1, units = units) 
    if (floor) calc = as.integer(floor(calc)) 
    calc 
} 

2016年はうるう年で、6月に開始時刻と終了時刻の間に年齢を決定することができます:ここで

は、私がこれまで持っているものの説明図です。それは30日でなければなりません。私は「年に同じ間隔を計算する場合

require(lubridate) 
#Consider month of June 2016, known to have 30 days 
from  = as.POSIXct("2016-6-1") 
to   = from + months(1) 

daysInYear = 365 + leap_year(to) 
age(from,to,units='days')    #30.00, CORRECT 
age(from,to,units='years')*daysInYear #30.08, INCORRECT 
age(from,to,units='years')*365  #30.00, CORRECT ANSWER, WRONG DAYS IN YEAR 

、それを返します:0.08219178、間違っていた、年齢関数の期間除数は、うるう年であること2016年の会計処理されていないので、私がそれを必要とします0.08196721を計算します。これは、同じ値に(365/366)を掛けたものです。

2つの日付間の正確な年齢を調べ、うるう年を考慮し、間隔単位の完全な指定を許可する簡単な方法はありますか?

+0

'diff.Date'は、うるう年を考慮する必要があります。それがそうしていないというあなたの証拠はどこにありますか? –

+0

もう1つのdupe:[Rの生年月日から列を変更する方法](http://stackoverflow.com/q/27096485/903061) – Gregor

+0

diff.Dateを使用していないImは上記の例にあります。 –

答えて

0
is.leapyear=function(year){ 
    #http://en.wikipedia.org/wiki/Leap_year 
    return(((year %% 4 == 0) & (year %% 100 != 0)) | (year %% 400 == 0)) 
} 

age.hackr <- 
      function(from, to = today(), units = "years", floor = FALSE) { 
       if(is.leapyear(year(to))){ 
       calc = interval(from,to)/duration(num = 1, units = units) 
       if (floor) calc = as.integer(floor(calc)) 
       calc <- calc - 0.00022457 
       calc 
       } else{ 
       calc = interval(from,to)/duration(num = 1, units = units) 
       if (floor) calc = as.integer(floor(calc)) 
       calc 
       } 
      } 

age.hackr(from, to, units = "years") * 366 

[1] 30

+0

とにかく 'lubridate'を使用しているので、' lubridate :: leap_year() 'を使うことができます。それはあなたと同じですが、いくつかの入力チェックがあります。 – Gregor

関連する問題