0

I am trying to select a subset of a data frame where the date needs to be less than a (calculated/variable) date.

The following code throws an error:

loanFrame_excluding_young <- loanFrame[loanFrame$LoanEffective < AddMonths(as.Date("2015-11-11"),-loanFrame$TermMonths),]
Error in seq.Date(X[[i]], ...) : 'by' must be of length 1

Any ideas?

rebatoma
  • 734
  • 1
  • 17
  • 32
gmarais
  • 1,801
  • 4
  • 16
  • 32
  • 2
    Please give a reproductable example. Edit your question. – jogo Nov 11 '15 at 14:43
  • If you're unsure how, here's how to create a [reproducible example in R](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) – Heroka Nov 11 '15 at 14:46
  • That's a good point! Expect AddMonths by the next version of DescTools (0.99.16) to recycle all of its arguments. – Andri Signorell Nov 15 '15 at 12:40
  • AddMonths does now (0.99.17) recyle its arguments: library(DescTools) AddMonths(as.Date("2015-11-11"), -c(1,3,5,7)) [1] "2015-10-11" "2015-08-11" "2015-06-11" "2015-04-11" – Andri Signorell Jun 27 '16 at 07:33

1 Answers1

0

The problem lies with the DescTools::AddMonths function. in AddMonths(x, n, ceiling = TRUE) the n can only be a single number, not a vector.

Using the following code does work using the %m-% function of lubridate.

library(lubridate)

loanFrame <- data.frame(TermMonths = c(1,3,5,7), 
                        LoanEffective = as.Date(c("2015-09-15", "2015-08-05", "2015-10-01", "2015-06-25")))

loanFrame_excluding_young <- loanFrame[loanFrame$LoanEffective < as.Date("2015-11-11") %m-% months(loanFrame$TermMonths),]

loanFrame_excluding_young

  TermMonths LoanEffective
1          1    2015-09-15
2          3    2015-08-05
phiver
  • 23,048
  • 14
  • 44
  • 56