hms R Package

repository·main·Indexed 40 days ago

https://github.com/tidyverse/hms

An R package providing a class for storing and displaying durations or time-of-day values in a consistent hh:mm:ss format. It represents time as seconds since midnight to optimize data exchange with databases and spreadsheets, supporting values that exceed 24 hours or are negative.

Tokens
782
Snippets
3
Records
4
Agent score
0%

What's inside hms

  1. Overview of the hms class

    main

    The hms package provides a class for storing durations or time-of-day values, displayed in hh:mm:ss format. It is designed to simplify data exchange with databases and spreadsheets.

    Key features:

    • Internal Storage: Values are stored as a numeric vector representing the number of seconds since midnight.
    • Flexibility: Supports values that exceed the 24-hour boundary or are negative.
    • Precision: By default, displays fractional seconds up to a microsecond.
    • Integration: Based on the difftime class and can be used as a column in a data frame.
  2. How hms internal representation works

    main

    Objects of the hms class (and the underlying difftime class) are stored as the number of seconds since 00:00:00.

    To convert an hms object to its numeric underlying value, use as.numeric(). To convert a numeric value (seconds since midnight) back into an hms object, use as_hms().

    times <- parse_hms(c("00:00:00.25", "00:00:01", "00:01:30", "01:00:00"))
    
    # Convert to numeric (seconds since midnight)
    times_num <- as.numeric(times)
    # [1] 0.25 1.00 90.00 3600.00
    
    # Convert numeric back to hms
    as_hms(times_num)
    #> 00:00:00.25
    #> 00:00:01.00
    #> 00:01:30.00
    #> 01:00:00.00
  3. Install hms

    main

    You can install hms as part of the tidyverse suite, as a standalone package from CRAN, or via GitHub using pak.

    # Install the whole tidyverse:
    install.packages("tidyverse")
    
    # Install just hms:
    install.packages("hms")
    
    # Install the development version from GitHub:
    # install.packages("pak")
    pak::pak("tidyverse/hms")
  4. Use hms for time-of-day and durations

    main

    You can create hms objects using explicit time components, parsing strings, or coercing from POSIXt objects. The class can also be used directly within data frames.

    library(hms)
    
    # Construct from hours, minutes, and seconds
    hms(56, 34, 12)
    #> 12:34:56
    
    # Coerce from POSIXt (e.g., Sys.time())
    as_hms(Sys.time())
    #> 10:27:38.905625
    
    # Parse from a string
    parse_hms("12:34:56")
    #> 12:34:56
    
    # Coerce to POSIXct
    as.POSIXct(hms(1))
    #> [1] "1970-01-01 00:00:01 UTC"
    
    # Use as a column in a data frame
    data.frame(hours = 1:3, hms = hms(hours = 1:3))
    #>   hours      hms
    #> 1     1 01:00:00
    #> 2     2 02:00:00
    #> 3     3 03:00:00