R issue with rounding milliseconds

前端 未结 4 1238
孤街浪徒
孤街浪徒 2020-12-18 00:46

Given the following issue with rounding milliseconds under R. How do I get around it so that the times are correct?

> options(digits.secs=3)
> as.POSI         


        
4条回答
  •  青春惊慌失措
    2020-12-18 01:47

    I don't see that:

    > options(digits.secs = 4)
    > as.POSIXlt("13:29:56.061", format = '%H:%M:%OS', tz='UTC')
    [1] "2012-06-07 13:29:56.061 UTC"
    > as.POSIXlt("13:29:56.062", format = '%H:%M:%OS', tz='UTC')
    [1] "2012-06-07 13:29:56.062 UTC"
    > as.POSIXlt("13:29:56.063", format = '%H:%M:%OS', tz='UTC')
    [1] "2012-06-07 13:29:56.063 UTC"
    > options(digits.secs = 3)
    > as.POSIXlt("13:29:56.061", format = '%H:%M:%OS', tz='UTC')
    [1] "2012-06-07 13:29:56.061 UTC"
    > as.POSIXlt("13:29:56.062", format = '%H:%M:%OS', tz='UTC')
    [1] "2012-06-07 13:29:56.062 UTC"
    > as.POSIXlt("13:29:56.063", format = '%H:%M:%OS', tz='UTC')
    [1] "2012-06-07 13:29:56.063 UTC"
    

    with

    > sessionInfo()
    R version 2.15.0 Patched (2012-04-14 r59019)
    Platform: x86_64-unknown-linux-gnu (64-bit)
    
    locale:
     [1] LC_CTYPE=en_GB.utf8       LC_NUMERIC=C             
     [3] LC_TIME=en_GB.utf8        LC_COLLATE=en_GB.utf8    
     [5] LC_MONETARY=en_GB.utf8    LC_MESSAGES=en_GB.utf8   
     [7] LC_PAPER=C                LC_NAME=C                
     [9] LC_ADDRESS=C              LC_TELEPHONE=C           
    [11] LC_MEASUREMENT=en_GB.utf8 LC_IDENTIFICATION=C      
    
    attached base packages:
    [1] stats     graphics  grDevices utils     datasets  methods  
    [7] base
    

    With the "%OSn" format strings, one forces truncation. If the fractional second cannot be represented exactly in floating points then the truncation may very well go the wrong way. If you see things going to wrong way you can also round explicitly to the unit you want or add a half of the fraction you wish to operate at (in the case shown 0.0005):

    > t1 <- as.POSIXlt("13:29:56.061", format = '%H:%M:%OS', tz='UTC')
    > t1
    [1] "2012-06-07 13:29:56.061 UTC"
    > t1 + 0.0005
    [1] "2012-06-07 13:29:56.061 UTC"
    

    (but a I said, I don't see the problem here.)

    This latter point was made by Simon Urbanek on the R-Devel mailing list on 30-May-2012.

提交回复
热议问题