[R-SIG-Finance] Relative Date Question

Andrew Piskorski atp at piskorski.com
Thu Aug 28 16:24:10 CEST 2008


On Thu, Aug 28, 2008 at 11:14:58AM +0200, Ruvashen Padayachee wrote:
> Hi there. I have a quick query. What is the best way in R to find out a
> date relative to another date? 
>  
> For example, how can I find the date one month after "2008/09/30" ? 

One way is to simply fork off a small Tcl script, as Tcl's 'clock'
command includes pretty good support for relative date calculations,
getting the last day of the month, etc.  E.g.:

  my.next.month <- function(month) {
     # Given a single date anywhere in a month, get the next month date.
     # We assume here that 'month' is a string in YYYY-MM-DD format.
     tcl.code <-
        paste('set month_d [clock scan {'  ,month  ,'}]'
              ,'\n'  ,'puts [clock format [clock scan {+ 1 month} -base $month_d] -format {%Y-%m-%d}]'
              ,sep="")
     system("tclsh" ,input=tcl.code ,intern=T)
  }

  > my.next.month("2008-09-30")
  [1] "2008-10-30"
  > my.next.month("2008-01-29")
  [1] "2008-02-29"
  > my.next.month("2007-01-29")
  [1] "2007-02-28"

Instead of forking a script with system(), you could also probably use
.Tcl(), which gives you a single persistent in-processs Tcl
interpreter, and would presumably be more efficient.  E.g.:

  > capabilities("tcltk")
  tcltk
   TRUE
  > require(tcltk)
  Loading required package: tcltk
  Loading Tcl/Tk interface ... done
  > .Tcl("set x 1") ; .Tcl("incr x") ; .Tcl("incr x")
  <Tcl> 1
  <Tcl> 2
  <Tcl> 3

-- 
Andrew Piskorski <atp at piskorski.com>
http://www.piskorski.com/



More information about the R-SIG-Finance mailing list