The goal of this tutorial is to read dates in the POSIXct format. In addition we will learn how to create labels for different uses.
# First we load the libraries
library(dplyr)
##
## Attaching package: 'dplyr'
## The following objects are masked from 'package:stats':
##
## filter, lag
## The following objects are masked from 'package:base':
##
## intersect, setdiff, setequal, union
# In this tutorial we are going to use Date and time data
Time_table <- read.csv("timetable.csv", stringsAsFactors = FALSE)
str(Time_table)
## 'data.frame': 34584 obs. of 2 variables:
## $ Date: chr "16/12/06" "16/12/06" "16/12/06" "16/12/06" ...
## $ Time: chr "18:00:00" "19:00:00" "20:00:00" "21:00:00" ...
# First we are going to create a new column containing the full date_time
Time_table <- mutate(Time_table, DateTime = paste(Date, Time))
str(Time_table)
## 'data.frame': 34584 obs. of 3 variables:
## $ Date : chr "16/12/06" "16/12/06" "16/12/06" "16/12/06" ...
## $ Time : chr "18:00:00" "19:00:00" "20:00:00" "21:00:00" ...
## $ DateTime: chr "16/12/06 18:00:00" "16/12/06 19:00:00" "16/12/06 20:00:00" "16/12/06 21:00:00" ...
# Now we transform from text to date format variable
Time_table$DateTime <- strptime(Time_table$DateTime, "%d/%m/%y %H:%M:%S")
str(Time_table$DateTime)
## POSIXlt[1:34584], format: "2006-12-16 18:00:00" "2006-12-16 19:00:00" ...
# Finally we transform the time to POSIXct
Time_table$DateTime <- as.POSIXct(Time_table$DateTime)
str(Time_table)
## 'data.frame': 34584 obs. of 3 variables:
## $ Date : chr "16/12/06" "16/12/06" "16/12/06" "16/12/06" ...
## $ Time : chr "18:00:00" "19:00:00" "20:00:00" "21:00:00" ...
## $ DateTime: POSIXct, format: "2006-12-16 18:00:00" "2006-12-16 19:00:00" ...
In this tutorial we have learnt how to read dates and times and format them in the best way. In addition we have learnt how to create tags to aggregate or group_by depending on our specific needs.