3

It seems POSIXct class is not retained when x[, median(datetime) , by = group] although x[, median(datetime) ] returns a "POSIXct". Calling as.POSIXct returns the desired output though.

Is there a reason I need to call as.POSIXct explicitly?

Below is a reproducible example using the latest data.table version on CRAN.

require(data.table)

x = data.table(v = as.POSIXct(c('2019-07-05 00:00:01', 
'2019-07-05 00:00:02', '2019-07-05 00:00:03', 
'2019-07-05 00:00:04')), g = rep(1:2, each = 2))

o1 = x[, .( V1 = median(v) ) ]

o2 = x[,  .(V1 = median(v) ), by = g]

o3 = x[,  .(V1 = as.POSIXct( median(v) ) ), by = g]

class(o1$V1)
[1] "POSIXct" "POSIXt" 

class(o2$V1)
[1] "numeric"

class(o3$V1)
[1] "POSIXct" "POSIXt" 




my sessionInfo():

R version 3.6.0 (2019-04-26)
Platform: x86_64-pc-linux-gnu (64-bit)
Running under: Ubuntu 19.04

Matrix products: default
BLAS:   /usr/lib/x86_64-linux-gnu/blas/libblas.so.3.8.0
LAPACK: /usr/lib/x86_64-linux-gnu/lapack/liblapack.so.3.8.0

locale:
 [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C               LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
 [5] LC_MONETARY=en_US.UTF-8    LC_MESSAGES=en_US.UTF-8    LC_PAPER=en_US.UTF-8       LC_NAME=C                 
 [9] LC_ADDRESS=C               LC_TELEPHONE=C             LC_MEASUREMENT=en_US.UTF-8 LC_IDENTIFICATION=C       

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

other attached packages:
[1] data.table_1.12.2

loaded via a namespace (and not attached):
[1] compiler_3.6.0 tools_3.6.0   
Henrik
  • 65,555
  • 14
  • 143
  • 159
MihaiV
  • 148
  • 8
  • Can't reproduce your result (using data.table_1.12.3 dev. version on Windows). – s_baldur Jul 05 '19 at 09:34
  • relevant: https://stackoverflow.com/questions/26401116/median-returning-an-error-when-using-data-table-in-r – chinsoon12 Jul 05 '19 at 09:49
  • 6
    See #8 in [Bug fixes v1.12.3](https://github.com/Rdatatable/data.table/blob/master/NEWS.md#bug-fixes). Either install development version or wait for `1.12.4`. – Henrik Jul 05 '19 at 10:21
  • This is very curious. I tried with `mean` and it does return a `POSIXct`, therefore this must happen because of how the `median` function is defined. My guess: I suppose `median` turns the input vector to numeric, finds the index of the median from the numeric vector and then returns the input vector's *ith* index. I cannot explain why the return is numeric though. – Arturo Sbr Jul 05 '19 at 14:43
  • As @henrik mentioned this is a bug (more of an infelicity I'd say) which is now fixed in the development version. – MihaiV Jul 05 '19 at 16:18

0 Answers0