以時間進行計算
使用 POSIXct 物件進行計算,和使用 Date 物件是完全類似的。試著用以下程式碼來增加或減少 POSIXct 物件的時間:
now <- Sys.time()
now + 3600 # add an hour
now - 3600 * 24 # subtract a day
時間物件之間的加減也很直覺:
birth <- as.POSIXct("1879-03-14 14:37:23")
death <- as.POSIXct("1955-04-18 03:47:12")
einstein <- death - birth
einstein
你正在開發一個需要使用者登入與登出的網站。你想知道某位特定使用者在網站上停留的總時間與平均時間。這位使用者共登入 5 次,也登出 5 次。這些時間已經收集在工作環境中的向量 login 與 logout。
本練習屬於課程
R 中級
練習說明
- 計算向量
logout與login的差,也就是使用者每次獨立工作階段的上線時間。將結果存成變數time_online。 - 透過列印來檢視變數
time_online。 - 計算該使用者的總上線時間,並列印結果。
- 計算該使用者的平均上線時間,並列印結果。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# 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