使用R计算X个双月期的总天数

时间:2016-07-19 18:14:06

标签: r lubridate

> 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天发生)。

如果所有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

1 个答案:

答案 0 :(得分:1)

对您的代码稍作修改:

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(floor(df$term/2)) - df$begin_date), 
as.integer(df$begin_date %m+% months(floor(df$term/2)) - df$begin_date +15 )))

您需要在第二个ifelse

中添加额外的发言权