Calculations with Times
Calculations using POSIXct
objects are completely analogous to those using Date
objects. Try to experiment with this code to increase or decrease POSIXct
objects:
now <- Sys.time()
now + 3600 # add an hour
now - 3600 * 24 # subtract a day
Adding or subtracting time objects is also straightforward:
birth <- as.POSIXct("1879-03-14 14:37:23")
death <- as.POSIXct("1955-04-18 03:47:12")
einstein <- death - birth
einstein
You're developing a website that requires users to log in and out. You want to know what is the total and average amount of time a particular user spends on your website. This user has logged in 5 times and logged out 5 times as well. These times are gathered in the vectors login
and logout
, which are already defined in the workspace.
This exercise is part of the course
Intermediate R
Exercise instructions
- Calculate the difference between the two vectors
logout
andlogin
, i.e. the time the user was online in each independent session. Store the result in a variabletime_online
. - Inspect the variable
time_online
by printing it. - Calculate the total time that the user was online. Print the result.
- Calculate the average time the user was online. Print the result.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# login and logout are already defined in the workspace
# Calculate the difference between login and logout: time_online
# Inspect the variable time_online
# Calculate the total time online
# Calculate the average time online