Sum & Average of Hours, Minutes & Seconds in R (2 Examples)

This article illustrates how to calculate the sum and mean of a time object in the R programming language.

Creation of Example Data

x <- c("15:22:33", "03:12:11", "16:16:16")          # Example data
x                                                   # Display example data
# [1] "15:22:33" "03:12:11" "16:16:16"

Example 1: Get Sum of Hours, Minutes & Seconds

install.packages("lubridate")                       # Install & load lubridate
seconds_to_period(sum(period_to_seconds(hms(x))))   # Calculate sum
# [1] "1d 10H 51M 0S"

Example 2: Get Mean of Hours, Minutes & Seconds

seconds_to_period(mean(period_to_seconds(hms(x))))  # Calculate mean
# [1] "11H 37M 0S"

Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.
You need to agree with the terms to proceed