I want to create a vector of datetime object in C/C++ and then return them to R. In the documentation of POSIXct class it is written that it keeps seconds since 1970-01-01 as a vector of numeric values, so I guess there should be a way to do the conversion from double to POSIXct in C.
I have this C code and want to return POSIXct dates instead of REAL numbers.
SEXP func()
{
SEXP dates;
PROTECT(dates = allocVector(REALSXP, 2));
REAL(dates)[0] = 1402329599.12456;
REAL(dates)[1] = 1402329600.85404;
UNPROTECT(1);
return dates;
}
Easy as setting the class .
#include <R.h>
#include <Rdefines.h>
SEXP func()
{
SEXP dates, class;
PROTECT(dates = allocVector(REALSXP, 2));
REAL(dates)[0] = 1402329599.12456;
REAL(dates)[1] = 1402329600.85404;
class = PROTECT(allocVector(STRSXP, 2));
SET_STRING_ELT(class, 0, mkChar("POSIXct"));
SET_STRING_ELT(class, 1, mkChar("POSIXt"));
classgets(dates, class);
UNPROTECT(2);
return dates;
}
You might also want to set the tzone
attribute.
#include <R.h>
#include <Rdefines.h>
SEXP func()
{
SEXP dates, class, tz_attr;
PROTECT(dates = allocVector(REALSXP, 2));
REAL(dates)[0] = 1402329599.12456;
REAL(dates)[1] = 1402329600.85404;
class = PROTECT(allocVector(STRSXP, 2));
SET_STRING_ELT(class, 0, mkChar("POSIXct"));
SET_STRING_ELT(class, 1, mkChar("POSIXt"));
classgets(dates, class);
tz_attr = PROTECT(allocVector(STRSXP, 1));
SET_STRING_ELT(tz_attr, 0, mkChar("GMT"));
setAttrib(dates, install("tzone"), tz_attr);
UNPROTECT(3);
return dates;
}
你可以从R做强制:
r_func <- function( tz=NULL) .POSIXct(.Call("func"), tz)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.