2016-05-29 11 views
0

Rにはこれを行うための組み込みメソッドがあると思われますが、私はプログラミングが初めてで、日付間の日数を手として計算する方法を理解しようとしていました。ここに私のコードです:日付を手で計算する

isLeapYear <- function(year) { 
    if (year %% 400 == 0) { 
    return (TRUE) 
    } 
    if (year %% 100 == 0) { 
    return (FALSE) 
    } 
    if (year %% 4 == 0) { 
    return (TRUE) 
    } 
    else{ return (FALSE)} 
} 

daysInMonth <- function(year,month){ 
    if (month == 1 | month == 3| month == 5 | month == 7 | month == 8 | month == 10 | month == 12) { 
    return (31) 
    } 
    else if (month == 2){ 
    if (isLeapYear(year)){ 
     return (29) 
    } 
    else {return (28)} 
    } 
    else {return (30)} 
} 
nextDay <- function(year, month, day){ 
    if (day < daysInMonth(year,month)){ 
    return (list(year, month, day + 1)) 
    } 
    else{ 
    if (month == 12){ 
     return (list(year + 1, 1, 1)) 
    } 
    else{return (list(year, month + 1, 1))} 
    } 
} 

dateIsBefore <- function(year1, month1, day1, year2, month2, day2){ 
    if (year1 < year2){ 
    return(TRUE) 
    } 
    if (year1 == year2){ 
    if (month1 < month2){ 
     return(TRUE) 
    } 
    if (month1 == month2){ 
     return (day1 < day2) 
    } 
    } 
    return (FALSE) 
} 

daysBetweenDates <- function(year1, month1, day1, year2, month2, day2){ 
    days <- 0 
    while (dateIsBefore(year1, month1, day1, year2, month2, day2)){ 
    result = nextDay(year1,month1,day1) 
    year1 = result[1] 
    month1 = result[2] 
    day1 = result[3] 
    days = days+1 
    } 
    return (days) 
} 

私はPythonを使用して2つの日付の間の日数を決定するコードを書いています。私は今、私がやっている別の割り当てのためにそれをRに変換しようとしています。個々の関数を実行すると、うまく動作するように見えます。私はdaysBetweenDates(2012,1,1,2012,2,28)を呼び出すとき、私は次のエラーを取得する:ちょうどas.integer()を使用して差として数を取得する上でのコメントにディルクによって提案

Error in day + 1 : non-numeric argument to binary operator

+0

本当に必要なのは、 '-'です。 'asDate( '2015-01-01') - as.Date( '2013-01-01')' – alistaire

+0

私はrにこれを行うためのメソッドが組み込まれていると考えましたが、私はプログラミングが初めてで、練習として考えなさい。 –

答えて

2
> as.Date("2012/02/28") - as.Date("2012/01/01") 
# Time difference of 58 days 
> as.Date("2012/01/01") - as.Date("2012/02/28") 
# Time difference of -58 days 

改善が、ここでは

> as.integer(as.Date("2012/02/28") - as.Date("2012/01/01")) 
# [1] 58 
> as.integer(as.Date("2012/01/01") - as.Date("2012/02/28")) 
# [1] -58 
+2

正解です。例えば 'as.integer() 'などのように結果をキャストすると、数値解だけが得られます。 –

1

理由ですあなたのコードが機能していないのは、resultの3つの要素をyear1,month1day1に割り当てる方法が、whileのループ内にあるためです我々のdaysBetweenDates機能。あなたはそれが動作するはずです。このようにそれを変更する場合:return <- list(2012, 1, 1)を行い、その後、return[1]return[[1]]とその比較した場合

daysBetweenDates <- function(year1, month1, day1, year2, month2, day2){ 
    days <- 0 
    while (dateIsBefore(year1, month1, day1, year2, month2, day2)){ 
    result = nextDay(year1,month1,day1) 
    year1 = result[[1]] 
    month1 = result[[2]] 
    day1 = result[[3]] 
    days = days + 1 
    } 
    return (days) 
} 

あなたは違いが表示されるはずです。これは、リストを使用する際のよくある間違いです。サブセットの詳細については、http://adv-r.had.co.nz/Subsetting.htmlを参照してください。