[Rd] How to convert time_t to R date object

Dirk Eddelbuettel edd at debian.org
Sun Mar 16 15:55:44 CET 2014


On 16 March 2014 at 18:36, Bill Wang wrote:
| I am writing a R extensions, and I need pass time_t to R in C, but I don't
| know how to do.
| Can you give me some help? do not use double directly.

Just treat it as an int:

  R> library(Rcpp)
  R> cppFunction("Date time_t2date(time_t what) { return((int) what); }")
  R> time_t2date(0)
  [1] "1970-01-01"
  R> time_t2date( Sys.Date() )
  [1] "2014-03-16"
  R>


Here I use Rcpp to define the 'time_t2date' function on the fly. 

It takes the time_t and returns a Date type (which here is a C++ Date type
mapping to the R Date -- you can ignore that, but will have to write the
legwork yourself if you don't use Rcpp).  

As 'time_t' is 'long int' on my system, so I cast it to int. The rest is
automagic (thanks to RcpP).  

Notice that I also get today's date down and up correctly.

See 'Writing R Extensions' for the details at the C level. 

See the Rcpp documentation (and, if I may, my book) for details on Rcpp if
that interests you.

Dirk

-- 
Dirk Eddelbuettel | edd at debian.org | http://dirk.eddelbuettel.com



More information about the R-devel mailing list