Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R and Rscript give different results for datetime

Tags:

r

rstudio

rscript

When I try to execute the following code on RStudio

library(lubridate)
library(data.table)

a <- data.frame(c("2017-12-01 00:01:00","2017-12-02 00:01:00"),c(5,6))
colnames(a) <- c("t", "x")
a <- as.data.table(a)
a[, t := parse_date_time(t, orders = "ymd HMS")]
print(class(a$t))
paste("a:", format(a[1,1], format = "%Y-%m-%d %H:%M:%S"))

I have the following result:

[1] "a: 2017-12-01 00:01:00"

But when I try to run the same code under Rscript, the output is

[1] "a: 1"

Does anyone have the same problem as me? Any help is appreciated.

EDIT: R version 3.3.1, platform x86_64-w64-mingw32/x64.

Windows server 2012 version:

Major Minor Build Revision

6 2 9200 0

like image 884
Lucio Carlos Pimentel Paiva Avatar asked Dec 22 '17 19:12

Lucio Carlos Pimentel Paiva


1 Answers

The real problem is with data.table. In earlier versions of data.table, if we use numeric index, without with=FALSE, then it will return the numeric index itself. Hence the output, shared in question. For details on this, one can go through the documentation of data.table.

In recent versions of data.table, however, this issue has been resolved, and as a result, data.table pretty much works like data.frame. This is the reason, why no one was able to replicate the output shared in the question.

Below is the updated code, using with=FALSE option with data.table.

library(lubridate)
library(data.table)

a <- data.frame(c("2017-12-01 00:01:00","2017-12-02 00:01:00"),c(5,6), stringsAsFactors=FALSE) # stringsAsFactors=TRUE
colnames(a) <- c("t", "x")
a$t1 <- parse_date_time(a$t, orders = "ymd HMS")
a <- as.data.table(a)
a[, t := parse_date_time(as.character(t), orders = "ymd HMS")]
print(class(a$t))
paste("a:", format(a[1,1, with=FALSE], format = "%Y-%m-%d %H:%M:%S"))

You can get info on package version using using sessionInfo(). Using the package versions, the issue can be identified.

like image 170
Kumar Manglam Avatar answered Oct 22 '22 18:10

Kumar Manglam