0
> df <- data.frame(begin_date = as.Date("2016-01-01") + c(1:10),
+ term = c(11:20),
+ term_unit = c(rep("bimonthly", 5), rep("monthly", 5))
+ )
> df
begin_date term term_unit
1 2016-01-02 11 bimonthly
2 2016-01-03 12 bimonthly
3 2016-01-04 13 bimonthly
4 2016-01-05 14 bimonthly
5 2016-01-06 15 bimonthly
6 2016-01-07 16 monthly
7 2016-01-08 17 monthly
8 2016-01-09 18 monthly
9 2016-01-10 19 monthly
10 2016-01-11 20 monthly
我想計算每行的期限天數。貸款從begin_date開始,然後借款人在期限欄中顯示每月或雙月(每月兩次)付款的次數。因此,在開始日期後一個月,第一次計劃的月付款將會發生,第二次計劃的雙月付款將發生(第一個雙月會在begin_date後15天發生)。使用R來計算X個雙月期的總天數
如果所有term_units是每月我可以計算天
> library(lubridate)
df$term_days <- as.integer(df$begin_date %m+% months(df$term) - df$begin_date)
的個數,但我遇到麻煩時,我嘗試和計算天數爲雙月刊條款。
> df$term_days <- ifelse(df$term_unit == "monthly", as.integer(df$begin_date %m+% months(df$term) - df$begin_date),
+ ifelse((df$term/2) == floor(df$term/2), as.integer(df$begin_date %m+% months(df$term/2) - df$begin_date),
+ as.integer(df$begin_date %m+% months(floor(df$term/2)) - df$begin_date +15)))
返回錯誤
Error in validObject(.Object) :
invalid class 「Period」 object: periods must have integer values
我設法得到它通過在第二行中將'%m +%個月(df $ term/2)'更改爲'%m +%months(floor(df $ term/2))'來工作。如果有人有更優雅的解決方案,我很樂意看到它。 – liamvt