Introduction to Time Series Analysis and R
Time series data is one of the most common formats of data, and it is used to describe an event or phenomena that occurs over time. Time series data has a simple requirement—its values need to be captured at equally spaced time intervals, such as seconds, minutes, hours, days, months,e.t.c
The UK hourly demand for electricity
The S&P 500 daily closing values
The US monthly unemployment rate
The annual number of sunspots
+
Seasonality: If we look at graph 1, there is high
demand during the day and low demand during the night time.
Trend: A clear upper trend can be seen in graph 2 that’s between 2013 and 2017.
Cycles: We can see cyclic patterns in both graph 3 and graph 4.
Correlation: Although S&P 500 and the US unemployment rate are presented with different frequencies, you can see that the unemployment rate has decreased since 2013 (negative trend)
Data collection
Data preparation
Descriptive analysis
Predictive analysis
Assignment operators
Arithmetic operators
Logical operators
Relational operators
# Assignment operators
a <- "Hello World"
a
## [1] "Hello World"
class(a)
## [1] "character"
b <- a
b
## [1] "Hello World"
# Arithmetic operators
x <- 10
y <- 2
x + y
## [1] 12
x/ 2.5
## [1] 4
y ^ 3
## [1] 8
# Logical operators
# The following are reserved names in R for Boolean objects:
# TRUE, FALSE or their shortcut T and F
a <- TRUE
b <- FALSE
# We can also test if a Boolean object is TRUE or FALSE
isTRUE(a)
## [1] TRUE
## [1] TRUE
isTRUE(b)
## [1] FALSE
## [1] FALSE
# The AND operator
a & b
## [1] FALSE
# The OR operator
a | b
## [1] TRUE
# The NOT operator
!a
## [1] FALSE
# The AND operator will return TRUE only if both a and b are TRUE
if (a & b) {print("a AND b is true")
} else {
print("a And b is false")
}
## [1] "a And b is false"
# Relational operators
# Assign for variables a and b the value 5, and 7 to c
a <- b <- 5
c <- 7
if(a == b){
print("a is equal to b")
} else{
print("a is not equal to b")
}
## [1] "a is equal to b"
d <- ifelse(test = a >= c,
yes = "a is greater or equal to c",
no = "a is smaller than c" )
d
## [1] "a is smaller than c"
Here, the ifelse function has three arguments: + test: Evaluates a logical test
yes: Defines what should be the output if the test result is TRUE
no: Defines what should be the output if the test result is FALSE
Note: You can use this function to install more than one package at once by using a vector type of input: install.packages(c(“lubridate”,“dplyr”,“h2o”))
search()
## [1] ".GlobalEnv" "package:stats" "package:graphics"
## [4] "package:grDevices" "package:utils" "package:datasets"
## [7] "package:methods" "Autoloads" "package:base"
library(TSstudio)
## Warning: package 'TSstudio' was built under R version 4.5.1
search()
## [1] ".GlobalEnv" "package:TSstudio" "package:stats"
## [4] "package:graphics" "package:grDevices" "package:utils"
## [7] "package:datasets" "package:methods" "Autoloads"
## [10] "package:base"
detach("package:TSstudio", unload=TRUE)
search()
## [1] ".GlobalEnv" "package:stats" "package:graphics"
## [4] "package:grDevices" "package:utils" "package:datasets"
## [7] "package:methods" "Autoloads" "package:base"
library(TSstudio)
## Warning: package 'TSstudio' was built under R version 4.5.1
search()
## [1] ".GlobalEnv" "package:TSstudio" "package:stats"
## [4] "package:graphics" "package:grDevices" "package:utils"
## [7] "package:datasets" "package:methods" "Autoloads"
## [10] "package:base"
library(ggplot2)
## Warning: package 'ggplot2' was built under R version 4.5.1
library(plotly)
## Warning: package 'plotly' was built under R version 4.5.1
##
## Attaching package: 'plotly'
## The following object is masked from 'package:ggplot2':
##
## last_plot
## The following object is masked from 'package:stats':
##
## filter
## The following object is masked from 'package:graphics':
##
## layout
search()
## [1] ".GlobalEnv" "package:plotly" "package:ggplot2"
## [4] "package:TSstudio" "package:stats" "package:graphics"
## [7] "package:grDevices" "package:utils" "package:datasets"
## [10] "package:methods" "Autoloads" "package:base"
### Flat files
file_url <- "https://github.com/PacktPublishing/Hands-On-Time-Series-Analysis-with-R/blob/master/Chapter01/TOTALNSA.csv"
file_url
## [1] "https://github.com/PacktPublishing/Hands-On-Time-Series-Analysis-with-R/blob/master/Chapter01/TOTALNSA.csv"
df1 <- read.csv(file = file_url, stringsAsFactors = FALSE)
## Warning in scan(file = file, what = what, sep = sep, quote = quote, dec = dec,
## : EOF within quoted string
class(df1)
## [1] "data.frame"
str(df1)
## 'data.frame': 1073 obs. of 1 variable:
## $ X..DOCTYPE.html.: chr "<html" " lang=en" " " " data-color-mode=auto data-light-theme=light data-dark-theme=dark" ...
View(df1)
library(Quandl)
## Warning: package 'Quandl' was built under R version 4.5.1
## Loading required package: xts
## Warning: package 'xts' was built under R version 4.5.1
## Loading required package: zoo
## Warning: package 'zoo' was built under R version 4.5.1
##
## Attaching package: 'zoo'
## The following objects are masked from 'package:base':
##
## as.Date, as.Date.numeric
#df2 <- Quandl(code = "FRED/TOTALNSA",
#type = "raw",
#collapse = "monthly",
#order = "asc",
#end_date="2017-12-31")
data("USVSales", package = "TSstudio")
class(USVSales)
## [1] "ts"
head(USVSales)
## Jan Feb Mar Apr May Jun
## 1976 885.2 994.7 1243.6 1191.2 1203.2 1254.7
US_V_Sales <- TSstudio::USVSales
US_V_Sales
## Jan Feb Mar Apr May Jun Jul Aug
## 1976 885.200 994.700 1243.600 1191.200 1203.200 1254.700 1162.300 1026.100
## 1977 969.900 1092.100 1451.100 1354.400 1377.100 1459.800 1202.000 1234.500
## 1978 931.300 1071.400 1480.600 1406.500 1557.600 1549.400 1289.200 1317.100
## 1979 1077.500 1148.700 1483.800 1304.600 1373.000 1183.800 1164.400 1207.200
## 1980 1042.000 1038.700 1141.900 946.600 893.800 932.700 1006.600 884.200
## 1981 814.300 949.200 1178.800 962.900 933.100 942.700 896.900 1009.000
## 1982 714.400 840.500 1057.300 877.200 1020.200 868.400 827.400 794.000
## 1983 789.300 821.600 1102.000 1012.300 1109.900 1205.400 1051.700 993.100
## 1984 1056.900 1158.900 1351.500 1245.800 1451.700 1315.900 1237.200 1129.600
## 1985 1196.600 1210.600 1391.000 1380.300 1498.900 1332.900 1337.600 1345.800
## 1986 1213.800 1182.200 1297.600 1390.100 1530.300 1426.500 1378.000 1344.100
## 1987 918.900 1148.400 1381.700 1385.300 1298.500 1419.600 1355.800 1400.600
## 1988 1122.500 1308.800 1505.000 1333.500 1455.400 1483.100 1302.800 1317.000
## 1989 1084.200 1127.300 1337.600 1354.800 1438.400 1329.200 1279.100 1441.900
## 1990 1161.300 1073.400 1295.200 1226.300 1332.100 1306.100 1244.400 1196.900
## 1991 839.300 927.500 1103.100 1059.600 1174.000 1175.300 1185.200 1063.000
## 1992 867.800 988.500 1128.400 1144.900 1169.700 1297.000 1158.200 1065.200
## 1993 915.300 976.100 1228.900 1273.500 1342.200 1383.100 1266.900 1158.800
## 1994 1045.500 1170.900 1472.200 1337.900 1382.100 1479.600 1219.500 1329.300
## 1995 1031.500 1128.700 1403.300 1216.000 1427.500 1477.200 1255.300 1365.200
## 1996 1050.600 1237.900 1404.400 1359.300 1522.900 1404.200 1317.300 1333.400
## 1997 1114.600 1177.400 1425.900 1310.300 1435.800 1355.000 1376.600 1348.200
## 1998 1044.100 1173.000 1405.500 1390.900 1543.900 1606.600 1264.900 1265.100
## 1999 1123.700 1325.700 1580.200 1451.700 1632.600 1651.400 1529.000 1523.600
## 2000 1239.300 1539.300 1713.000 1538.900 1664.900 1662.700 1468.600 1578.800
## 2001 1196.300 1381.500 1627.800 1377.000 1635.200 1652.200 1374.600 1478.200
## 2002 1129.999 1328.755 1541.215 1471.801 1538.496 1563.938 1551.996 1734.956
## 2003 1108.279 1237.619 1474.819 1436.733 1601.145 1502.328 1538.781 1656.167
## 2004 1149.668 1303.718 1540.321 1455.643 1660.854 1480.758 1589.173 1463.409
## 2005 1095.851 1286.074 1615.983 1542.051 1537.321 1720.006 1845.713 1524.158
## 2006 1176.162 1298.130 1576.647 1489.804 1533.712 1545.268 1531.114 1530.014
## 2007 1124.216 1285.136 1574.877 1365.965 1590.262 1481.210 1331.024 1500.386
## 2008 1063.408 1196.431 1378.605 1272.999 1420.485 1212.540 1156.003 1269.113
## 2009 670.466 701.635 872.848 832.588 938.410 874.874 1011.769 1274.678
## 2010 712.469 793.362 1083.953 997.334 1117.570 1000.455 1065.748 1011.564
## 2011 836.366 1007.082 1276.843 1173.520 1081.272 1071.229 1086.064 1094.479
## 2012 938.170 1175.820 1434.004 1204.471 1369.493 1310.158 1171.809 1305.342
## 2013 1065.798 1217.858 1479.427 1313.768 1473.275 1425.802 1335.833 1527.483
## 2014 1043.019 1221.370 1562.748 1408.232 1644.367 1451.814 1473.962 1607.315
## 2015 1177.910 1285.147 1579.627 1479.335 1668.452 1518.660 1546.818 1598.265
## 2016 1188.775 1374.272 1614.069 1524.100 1552.659 1548.860 1546.818 1539.790
## 2017 1164.323 1352.076 1582.674 1449.717 1543.862 1502.804 1441.011 1512.070
## 2018 1181.715 1328.140 1687.609 1391.226 1626.484 1586.664 1403.118 1527.416
## 2019 1171.503 1288.278 1642.750 1372.659 1628.074 1554.748 1443.947 1685.342
## Sep Oct Nov Dec
## 1976 1057.900 1129.400 1084.400 1061.800
## 1977 1104.600 1341.300 1181.600 1090.600
## 1978 1103.500 1397.000 1248.700 1068.500
## 1979 1029.600 1197.600 1018.600 959.700
## 1980 847.400 1043.400 870.500 821.400
## 1981 864.800 822.000 743.000 673.200
## 1982 891.100 840.900 971.500 839.300
## 1983 980.400 1126.000 1050.200 1054.000
## 1984 1053.400 1266.500 1141.100 1074.800
## 1985 1463.500 1243.200 1120.900 1198.800
## 1986 1733.600 1270.600 1119.900 1431.100
## 1987 1300.500 1193.200 1110.700 1249.200
## 1988 1223.200 1249.900 1191.100 1285.200
## 1989 1263.800 1116.900 1047.600 1011.900
## 1990 1144.800 1169.000 1000.500 987.200
## 1991 1062.200 1047.600 932.100 961.500
## 1992 1095.400 1132.200 988.600 1070.700
## 1993 1164.600 1182.500 1140.900 1152.700
## 1994 1252.100 1291.800 1197.900 1218.900
## 1995 1214.400 1226.000 1169.100 1202.600
## 1996 1231.400 1296.600 1146.400 1151.800
## 1997 1238.500 1282.000 1146.100 1287.700
## 1998 1314.400 1407.500 1176.400 1375.000
## 1999 1442.500 1396.800 1317.200 1440.600
## 2000 1506.300 1367.700 1260.900 1271.200
## 2001 1312.500 1753.200 1347.900 1336.100
## 2002 1250.986 1331.090 1227.557 1467.708
## 2003 1329.499 1333.497 1285.360 1463.264
## 2004 1470.081 1370.093 1231.197 1583.603
## 2005 1366.930 1184.160 1200.786 1525.713
## 2006 1394.215 1260.626 1236.584 1476.413
## 2007 1335.814 1256.533 1200.511 1414.147
## 2008 984.592 859.026 763.936 916.120
## 2009 759.633 853.942 761.865 1049.270
## 2010 973.954 965.135 888.085 1162.897
## 2011 1076.037 1048.258 1028.774 1268.462
## 2012 1206.182 1119.148 1169.803 1375.084
## 2013 1152.814 1235.532 1271.446 1383.676
## 2014 1272.036 1312.329 1324.117 1538.534
## 2015 1474.925 1486.420 1358.777 1671.288
## 2016 1462.065 1397.057 1399.375 1717.933
## 2017 1553.133 1385.649 1424.527 1639.555
## 2018 1474.997 1405.908 1422.219 1665.906
## 2019 1315.632 1380.180 1446.483 1565.023
class(US_V_Sales)
## [1] "ts"
length(US_V_Sales)
## [1] 528
matrix (base): This is the basic matrix format and is based on the numeric index of rows and columns.
data.frame (base): It includes additional attributes, which support the combination of multiple classes in the same table and different indexing methods.
ts (stats) and mts (stats): This is R’s built-in function for time series data, where ts is designed to be used with single time series data and multiple time series (mts) supports multiple time series data
zoo (zoo) and xts (xts): Both are designated data structures for time series data and are based on the matrix format with a timestamp index.
data("iris", package = "datasets")
str(iris)
## 'data.frame': 150 obs. of 5 variables:
## $ Sepal.Length: num 5.1 4.9 4.7 4.6 5 5.4 4.6 5 4.4 4.9 ...
## $ Sepal.Width : num 3.5 3 3.2 3.1 3.6 3.9 3.4 3.4 2.9 3.1 ...
## $ Petal.Length: num 1.4 1.4 1.3 1.5 1.4 1.7 1.4 1.5 1.4 1.5 ...
## $ Petal.Width : num 0.2 0.2 0.2 0.2 0.2 0.4 0.3 0.2 0.2 0.1 ...
## $ Species : Factor w/ 3 levels "setosa","versicolor",..: 1 1 1 1 1 1 1 1 1 1 ...
summary(iris)
## Sepal.Length Sepal.Width Petal.Length Petal.Width
## Min. :4.300 Min. :2.000 Min. :1.000 Min. :0.100
## 1st Qu.:5.100 1st Qu.:2.800 1st Qu.:1.600 1st Qu.:0.300
## Median :5.800 Median :3.000 Median :4.350 Median :1.300
## Mean :5.843 Mean :3.057 Mean :3.758 Mean :1.199
## 3rd Qu.:6.400 3rd Qu.:3.300 3rd Qu.:5.100 3rd Qu.:1.800
## Max. :7.900 Max. :4.400 Max. :6.900 Max. :2.500
## Species
## setosa :50
## versicolor:50
## virginica :50
##
##
##
iris[1:5,2]
## [1] 3.5 3.0 3.2 3.1 3.6
iris$Sepal.Width[1:5]
## [1] 3.5 3.0 3.2 3.1 3.6
iris$Sepal.Width[1:5]
## [1] 3.5 3.0 3.2 3.1 3.6
iris[1:5, "Sepal.Width"]
## [1] 3.5 3.0 3.2 3.1 3.6
iris[1:5, which(colnames(iris) == "Sepal.Width")]
## [1] 3.5 3.0 3.2 3.1 3.6
Setosa_df1 <- subset(x = iris, iris$Species == "setosa")
Setosa_df1
## Sepal.Length Sepal.Width Petal.Length Petal.Width Species
## 1 5.1 3.5 1.4 0.2 setosa
## 2 4.9 3.0 1.4 0.2 setosa
## 3 4.7 3.2 1.3 0.2 setosa
## 4 4.6 3.1 1.5 0.2 setosa
## 5 5.0 3.6 1.4 0.2 setosa
## 6 5.4 3.9 1.7 0.4 setosa
## 7 4.6 3.4 1.4 0.3 setosa
## 8 5.0 3.4 1.5 0.2 setosa
## 9 4.4 2.9 1.4 0.2 setosa
## 10 4.9 3.1 1.5 0.1 setosa
## 11 5.4 3.7 1.5 0.2 setosa
## 12 4.8 3.4 1.6 0.2 setosa
## 13 4.8 3.0 1.4 0.1 setosa
## 14 4.3 3.0 1.1 0.1 setosa
## 15 5.8 4.0 1.2 0.2 setosa
## 16 5.7 4.4 1.5 0.4 setosa
## 17 5.4 3.9 1.3 0.4 setosa
## 18 5.1 3.5 1.4 0.3 setosa
## 19 5.7 3.8 1.7 0.3 setosa
## 20 5.1 3.8 1.5 0.3 setosa
## 21 5.4 3.4 1.7 0.2 setosa
## 22 5.1 3.7 1.5 0.4 setosa
## 23 4.6 3.6 1.0 0.2 setosa
## 24 5.1 3.3 1.7 0.5 setosa
## 25 4.8 3.4 1.9 0.2 setosa
## 26 5.0 3.0 1.6 0.2 setosa
## 27 5.0 3.4 1.6 0.4 setosa
## 28 5.2 3.5 1.5 0.2 setosa
## 29 5.2 3.4 1.4 0.2 setosa
## 30 4.7 3.2 1.6 0.2 setosa
## 31 4.8 3.1 1.6 0.2 setosa
## 32 5.4 3.4 1.5 0.4 setosa
## 33 5.2 4.1 1.5 0.1 setosa
## 34 5.5 4.2 1.4 0.2 setosa
## 35 4.9 3.1 1.5 0.2 setosa
## 36 5.0 3.2 1.2 0.2 setosa
## 37 5.5 3.5 1.3 0.2 setosa
## 38 4.9 3.6 1.4 0.1 setosa
## 39 4.4 3.0 1.3 0.2 setosa
## 40 5.1 3.4 1.5 0.2 setosa
## 41 5.0 3.5 1.3 0.3 setosa
## 42 4.5 2.3 1.3 0.3 setosa
## 43 4.4 3.2 1.3 0.2 setosa
## 44 5.0 3.5 1.6 0.6 setosa
## 45 5.1 3.8 1.9 0.4 setosa
## 46 4.8 3.0 1.4 0.3 setosa
## 47 5.1 3.8 1.6 0.2 setosa
## 48 4.6 3.2 1.4 0.2 setosa
## 49 5.3 3.7 1.5 0.2 setosa
## 50 5.0 3.3 1.4 0.2 setosa
head(Setosa_df1)
## Sepal.Length Sepal.Width Petal.Length Petal.Width Species
## 1 5.1 3.5 1.4 0.2 setosa
## 2 4.9 3.0 1.4 0.2 setosa
## 3 4.7 3.2 1.3 0.2 setosa
## 4 4.6 3.1 1.5 0.2 setosa
## 5 5.0 3.6 1.4 0.2 setosa
## 6 5.4 3.9 1.7 0.4 setosa
Setosa_df2 <- iris[which(iris$Species == "setosa"), ]
head(Setosa_df2)
## Sepal.Length Sepal.Width Petal.Length Petal.Width Species
## 1 5.1 3.5 1.4 0.2 setosa
## 2 4.9 3.0 1.4 0.2 setosa
## 3 4.7 3.2 1.3 0.2 setosa
## 4 4.6 3.1 1.5 0.2 setosa
## 5 5.0 3.6 1.4 0.2 setosa
## 6 5.4 3.9 1.7 0.4 setosa
identical(Setosa_df1, Setosa_df2)
## [1] TRUE
summary(Setosa_df1)
## Sepal.Length Sepal.Width Petal.Length Petal.Width
## Min. :4.300 Min. :2.300 Min. :1.000 Min. :0.100
## 1st Qu.:4.800 1st Qu.:3.200 1st Qu.:1.400 1st Qu.:0.200
## Median :5.000 Median :3.400 Median :1.500 Median :0.200
## Mean :5.006 Mean :3.428 Mean :1.462 Mean :0.246
## 3rd Qu.:5.200 3rd Qu.:3.675 3rd Qu.:1.575 3rd Qu.:0.300
## Max. :5.800 Max. :4.400 Max. :1.900 Max. :0.600
## Species
## setosa :50
## versicolor: 0
## virginica : 0
##
##
##
Help and additional resources
Stack Overflow
GitHub
Package documentation and vignettes
Google it ### Summary This chapter provided an overview of time series analysis with R. We started with the basic definition of time series data and the analysis process, which we will use throughout this book
In this chapter, we will cover the following topics: + The date and time formats + Date and time objects in R + Creating a date or time index + Manipulation of date and time with lubridate package
One of the main challenges of working with date and time objects is the variety of formats that can be used for representing date and time.
Date and time objects in R <>
Date: This is a simple representation of a calendar date following the ISO 8601 international standard format (or the Gregorian calendar format) using the YYYY-m-d date format. Each date object has a numeric value of the number of days since the origin point (the default setting is 1970-01-01). In the Handling numeric date objects section in this chapter, we will discuss the usage of the origin in the reformatting process of date objects in more detail. It will make sense to use this format when the frequency of the data is daily or lower (for example, monthly, quarterly, and so on) and the time of the day doesn’t matter.
POSIXct/POSIXlt: Also known as the DateTime classes (that is, they represent both date and time), these are two POSIX date/time classes that represent the calendar date, the time of the day, and the time zone using the ISO 8601 international standard format of YYYY-m-d H:M:S. The main difference between the two is the form in which the values are stored internally. The POSIXct class, similar to the Date class, represents the (signed) number of seconds since the origin point (1970-01-01, UTC time zone) as a numeric vector. On the other hand, the POSIXlt class stores each one of the date and time elements as a list.
R has a structural method to assign values to a specific class or object, which is usually the combination of as.[the class name]. As long as the assigned object follows the relevant format, the creation of the object is fairly simple. For instance, we can convert the “2014-5-12” string into a Date object using the as.Date function: date <- as.Date(“2014-5-12”) date
date <- as.Date("2014-5-12")
date
## [1] "2014-05-12"
date <- Sys.Date()
date
## [1] "2025-10-08"
time_ct <- Sys.time()
time_ct
## [1] "2025-10-08 12:40:06 WAT"
class(date)
## [1] "Date"
class(time_ct)
## [1] "POSIXct" "POSIXt"
time_it <- as.POSIXlt(time_ct)
time_it
## [1] "2025-10-08 12:40:06 WAT"
class(time_it)
## [1] "POSIXlt" "POSIXt"
Last but not least, even if your objects are already reformatted to the ISO 8601 standard, in some cases, the attributes are lost and R will automatically classify it as a string or categorical variable (if the stringsAsFactors function is set to TRUE)
Reformatting or converting date objects is the process of transforming a non-date (or POSIXct/lt) object such as character or numeric to a Date format (or POSIXct/lt).
url <- "https://rpubs.com/Mr_Isaac/1350838"
url
## [1] "https://rpubs.com/Mr_Isaac/1350838"
dates_df <- read.csv(url, stringsAsFactors = FALSE)
class(dates_df)
## [1] "data.frame"
str(dates_df)
## 'data.frame': 262 obs. of 1 variable:
## $ X..DOCTYPE.html.: chr "<html>" "<head>" "<meta content='IE=edge' http-equiv='X-UA-Compatible'>" "<meta content='width=800' name='viewport'>" ...
Sys.timezone()
## [1] "Africa/Lagos"
time_str <- "2018-12-31 23:59:59"
time_default_tz <- as.POSIXct(time_str)
time_assign_tz <- as.POSIXct(time_str, tz = "GMT")
print(c(time_default_tz, time_assign_tz))
## [1] "2018-12-31 23:59:59 WAT" "2019-01-01 00:59:59 WAT"
class(date)
## [1] "Date"
class(time_ct)
## [1] "POSIXct" "POSIXt"
time_lt <- as.POSIXlt(time_ct)
time_lt
## [1] "2025-10-08 12:40:06 WAT"
class(time_lt)
## [1] "POSIXlt" "POSIXt"
unclass(time_ct)
## [1] 1759923607
unclass(time_lt)
## $sec
## [1] 6.963203
##
## $min
## [1] 40
##
## $hour
## [1] 12
##
## $mday
## [1] 8
##
## $mon
## [1] 9
##
## $year
## [1] 125
##
## $wday
## [1] 3
##
## $yday
## [1] 280
##
## $isdst
## [1] 0
##
## $zone
## [1] "WAT"
##
## $gmtoff
## [1] 3600
##
## attr(,"tzone")
## [1] "" "WAT" " "
## attr(,"balanced")
## [1] TRUE
daily_index <- seq.Date(from = as.Date("2016-01-01"), # Starting date
to = as.Date("2018-12-31"), # Ending date
by = "day") # Defining the time intervals
head(daily_index)
## [1] "2016-01-01" "2016-01-02" "2016-01-03" "2016-01-04" "2016-01-05"
## [6] "2016-01-06"
daily_3_index <- seq.Date(from = as.Date("2016-01-01"),
to = as.Date("2018-12-31"),
by = "3 days")
head(daily_3_index)
## [1] "2016-01-01" "2016-01-04" "2016-01-07" "2016-01-10" "2016-01-13"
## [6] "2016-01-16"
hourly_index <- seq.POSIXt(from = as.POSIXct("2018-06-01"), by = "hours",
length.out = 48)
str(hourly_index)
## POSIXct[1:48], format: "2018-06-01 00:00:00" "2018-06-01 01:00:00" "2018-06-01 02:00:00" ...
time_US_str <- "Monday, December 31, 2018 11:59:59 PM"
time_base <- as.POSIXct(time_US_str,
format = "%A, %B %d, %Y %I:%M:%S %p")
library(lubridate)
## Warning: package 'lubridate' was built under R version 4.5.1
##
## Attaching package: 'lubridate'
## The following objects are masked from 'package:base':
##
## date, intersect, setdiff, union
time_lubridate <- mdy_hms(time_US_str, tz = "EST")
time_lubridate
## [1] "2018-12-31 23:59:59 EST"
dates_df <- read.csv(url, stringsAsFactors = FALSE)
dates_df
## X..DOCTYPE.html.
## 1 <html>
## 2 <head>
## 3 <meta content='IE=edge' http-equiv='X-UA-Compatible'>
## 4 <meta content='width=800' name='viewport'>
## 5 <title>RPubs - dates formats </title>
## 6 <meta name=csrf-param content=authenticity_token />
## 7 <meta name=csrf-token content=QEXB4XArByS3PwqmLngn8pAJDtxM1GBgeYy130E0C-vUSCxvHbhVvkHpinyPgXfWJcyd4Meuu6mUHohox2NSkQ />
## 8 <link rel=stylesheet href=/assets/application-798c5c8185e0577f32ef6e494dc6f4844600dab47b198e609bdfdfc5c2bd1ba6.css media=all />
## 9 <link rel=stylesheet href=/assets/pub/show-bd33ac3577cad80ddfffbc9a91fd52ff5a1492004beda059d971361a49a8afe9.css media=all />
## 10 <script src=/assets/application-f0c30dc3dc92395deb81849f84afdb351879582dcbbd6f2706a66bff0524a8fc.js></script>
## 11 <link rel=stylesheet href=https://use.typekit.net/tzi3tjz.css>
## 12 <script>
## 13 (function(i
## 14 s
## 15 o
## 16 g
## 17 r
## 18 a
## 19 m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
## 20 (i[r].q=i[r].q||[]).push(arguments)}
## 21 i[r].l=1*new Date();a=s.createElement(o)
## 22 m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a
## 23 m)
## 24 })(window
## 25 document
## 26 'script'
## 27 'https://www.google-analytics.com/analytics.js'
## 28 'ga');
## 29 ga('create'
## 30 'UA-20375833-3'
## 31 'auto'
## 32 {'allowLinker': true});
## 33 ga('require'
## 34 'linker');
## 35 ga('linker:autoLink'
## 36 ['rstudio.com'
## 37 'rstudio.github.io'
## 38 'rviews.rstudio.com'
## 39 'community.rstudio.com'
## 40 'rpubs.rstudio.com'
## 41 'environments.rstudio.com'
## 42 'rstudio.org'
## 43 'dailies.rstudio.com'
## 44 'pages.rstudio.com'
## 45 'db.rstudio.com'
## 46 'solutions.rstudio.com'
## 47 'docs.rstudio.com'
## 48 'spark.rstudio.com'
## 49 'shiny.rstudio.com'
## 50 'education.rstudio.com'
## 51 'rstudio.cloud'
## 52 'shinyapps.io'
## 53 'teamadmin.rstudio.com'
## 54 'blog.rstudio.com'
## 55 'support.rstudio.com'] );
## 56 ga('send'
## 57 'pageview');
## 58 </script>
## 59 </head>
## 60 <body class='show-pub show-toolbars'>
## 61 <div class='modal' id='login' style='display: none'>
## 62 <div class='modal-header'>
## 63 <h1>Sign In</h1>
## 64 </div>
## 65 <div class='modal-body'>
## 66 <div class='alert' id='login_message' style='display: none'></div>
## 67 <form action=/auth/login accept-charset=UTF-8 method=post><input name=utf8 type=hidden value=✓ autocomplete=off /><input type=hidden name=authenticity_token value=6MBK82kR4XJB1kpinh46eE0L_fiHKUihyv1IPVURT39r5PzOAjhSzyMza3em1kJweUYZVKB_aRWk7Imc8E2mBw autocomplete=off /><input name='return_url' type='hidden' value=''>
## 68 <div class='fieldset'>
## 69 <div class='control-group'>
## 70 <label class='control-label' for='login_username'>Username or Email</label>
## 71 <div class='controls'>
## 72 <input class='input-xlarge' id='login_username' name='username' type='text'>
## 73 </div>
## 74 </div>
## 75 <div class='control-group'>
## 76 <label class='control-label' for='login_password'>Password</label>
## 77 <div class='controls'>
## 78 <input class='input-xlarge' id='login_password' name='password' type='password'>
## 79 </div>
## 80 </div>
## 81 <div class='control-group'>
## 82 <a href='/auth/passwordhelp' target='_blank'>Forgot your password?</a>
## 83 </div>
## 84 </div>
## 85 </form>
## 86 </div>
## 87 <div class='modal-footer'>
## 88 <button class='btn btn-primary' id='login-modal-submit'>Sign In</button>
## 89 <button class='btn' id='login-modal-cancel'>Cancel</button>
## 90 </div>
## 91 </div>
## 92 <div class='navbar-inner' id='pageheader'>
## 93 <div id='branding'>
## 94 <h1 id='logo'>
## 95 <a href='/'><span id='R'>R</span>Pubs
## 96 </a>
## 97 </h1>
## 98 <span id='tagline'>by RStudio</span>
## 99 </div>
## 100 <div id='identity'>
## 101 <div class='btn-group'>
## 102 <a class='btn btn-inverse btn-small pull-right' href='#' onclick='rpubs_showLogin(); return false'>
## 103 Sign in
## 104 </a>
## 105 <a class='btn btn-inverse btn-small pull-right' href='/users/new'>
## 106 Register
## 107 </a>
## 108 </div>
## 109 </div>
## 110 </div>
## 111 <div id='pagebody'>
## 112 <div id='payload'>
## 113 <iframe allow='fullscreen' src='//rstudio-pubs-static.s3.amazonaws.com/1350838_44c7e92c118e47c490e7f698ca672d60.html'></iframe>
## 114 <button class='btn btn-tiny' id='btn-show-toolbars'>
## 115 <i class='icon-resize-small'></i>
## 116 </button>
## 117 </div>
## 118 <div class='navbar navbar-fixed-bottom' id='pagefooter'>
## 119 <div class='navbar-inner'>
## 120 <div class='container-fluid'>
## 121 <ul class='nav' id='pubmeta'>
## 122 <li id='pubtitle'>
## 123 <label>dates formats </label>
## 124 </li>
## 125 <li id='pubauthor'>
## 126 <a href=https://rpubs.com/Mr_Isaac>by ISAAC</a>
## 127 </li>
## 128 <li id='pubtime'>
## 129 <label>
## 130 Last updated
## 131 <time datetime='2025-10-02T09:23:38+00:00'>6 days ago</time>
## 132 </label>
## 133 </li>
## 134 </ul>
## 135 <ul class='nav pull-right'>
## 136 <li>
## 137 <button class='btn btn-small btn-success' id='btn-comments'>
## 138 <i class='icon-comment icon-white'></i>
## 139 <span id='comment-verb-hide'>
## 140 Hide
## 141 </span>
## 142 Comments
## 143 <span id='comment-count'>
## 144 (–)
## 145 </span>
## 146 </button>
## 147 <button class='btn btn-small btn-info' id='btn-share'>
## 148 <i class='icon-share icon-white'></i>
## 149 Share
## 150 </button>
## 151 <button class='btn btn-small btn-inverse' id='btn-hide-toolbars'>
## 152 Hide Toolbars
## 153 </button>
## 154 </li>
## 155 </ul>
## 156 </div>
## 157 </div>
## 158 </div>
## 159 <div class='modal hide' id='modal-share'>
## 160 <div class='modal-body'>
## 161 <btn class='close' data-dismiss='modal' type='button'>×</btn>
## 162 <h2 class='first'>Post on:</h2>
## 163 <p>
## 164 <a class='btn btn-primary btn-large' href='https://twitter.com/intent/tweet?original_referer=http%3A%2F%2Frpubs.com%2FMr_Isaac%2F1350838&source=tweetbutton&text=dates%20formats%20&url=http%3A%2F%2Frpubs.com%2FMr_Isaac%2F1350838' onclick='window.open(this.href
## 165 ''
## 166 'menubar=no
## 167 toolbar=no
## 168 resizable=yes
## 169 scrollbars=yes
## 170 height=275
## 171 width=660');return false;'>
## 172 Twitter
## 173 </a>
## 174 <a class='btn btn-primary btn-large' href='https://www.facebook.com/sharer.php?u=http%3A%2F%2Frpubs.com%2FMr_Isaac%2F1350838&t=dates%20formats%20' onclick='window.open(this.href
## 175 ''
## 176 'menubar=no
## 177 toolbar=no
## 178 resizable=yes
## 179 scrollbars=yes
## 180 height=350
## 181 width=660');return false;'>
## 182 Facebook
## 183 </a>
## 184 <a class='btn btn-primary btn-large' href='https://plus.google.com/share?url=http%3A%2F%2Frpubs.com%2FMr_Isaac%2F1350838' onclick='window.open(this.href
## 185 ''
## 186 'menubar=no
## 187 toolbar=no
## 188 resizable=yes
## 189 scrollbars=yes
## 190 height=600
## 191 width=600');return false;'>
## 192 Google+
## 193 </a>
## 194 </p>
## 195 <hr>
## 196 <h3>Or copy & paste this link into an email or IM:</h3>
## 197 <input onclick='this.select()' readonly='readonly' value='http://rpubs.com/Mr_Isaac/1350838'>
## 198 </div>
## 199 </div>
## 200 <script>
## 201 $('#btn-edit').click(function() {
## 202 location.href = /Mr_Isaac/1350838/edit;
## 203 });
## 204 $('#btn-delete').mouseover(function() {
## 205 $('#btn-delete').removeClass('btn-inverse').addClass('btn-danger');
## 206 });
## 207 $('#btn-delete').mouseout(function() {
## 208 $('#btn-delete').addClass('btn-inverse').removeClass('btn-danger');
## 209 });
## 210 $('#btn-hide-toolbars').click(function() {
## 211 $(document.body).addClass('hide-toolbars');
## 212 $(document.body).removeClass('show-toolbars');
## 213 });
## 214 $('#btn-show-toolbars').click(function() {
## 215 $(document.body).addClass('show-toolbars');
## 216 $(document.body).removeClass('hide-toolbars');
## 217 });
## 218 $('#btn-share').click(function() {
## 219 $('#modal-share').modal().css({
## 220 'margin-left': function () {
## 221 return -($(this).width() / 2);
## 222 }
## 223 });
## 224 });
## 225 $('#btn-comments').click(function() {
## 226 $(document.body).toggleClass('show-comments');
## 227 });
## 228 setInterval(function() {
## 229 // Poll for comment count. Barf.
## 230 var text = $('#dsq-num-posts').text();
## 231 if (text && /^\\d+$/.test(text))
## 232 $('#comment-count').text('(' + text + ')');
## 233 }
## 234 1000);
## 235 </script>
## 236 <div id='comment-wrapper'>
## 237 <div id='disqus_thread'>
## 238 <script>
## 239 var disqus_config = function () {
## 240 // The generated payload which authenticates users with Disqus
## 241 this.page.remote_auth_s3 = 'e30= 786d434d41be0d096e37644cf39dafc0e8188c5c 1759923612';
## 242 this.page.author_s3 = 'eyJ1c2VybmFtZSI6InJwdWJzLTU0OTM1NyJ9 2ed710360f88e67044654e9d21b5dc994e326839 1759923612';
## 243 this.page.api_key = '7NhtlDm2Hf3z44e8I6PRkOLIwe9o1U0rVepc4PMzqwnADLCB3JhMdX7ZUPbnl85p';
## 244 };
## 245 </script>
## 246 <script>
## 247 var disqus_shortname = 'rpubs'; // required: replace example with your forum shortname
## 248 var disqus_identifier = 'pub-1350838';
## 249 var disqus_developer = 1;
## 250
## 251 /* * * DON'T EDIT BELOW THIS LINE * * */
## 252 (function() {
## 253 var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
## 254 dsq.src = '//' + disqus_shortname + '.disqus.com/embed.js';
## 255 (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
## 256 })();
## 257 </script>
## 258 </div>
## 259 </div>
## 260 </div>
## 261 </body>
## 262 </html>
library(Quandl)
# NGC <-Quandl(code = "FRED/NATURALGAS",
# collapse="quarterly",
# type = "ts",
# end_date = "2018-12-31")
# NGC
# class(NGC)
# plot.ts(NGC,
# main = "US Quarterly Natural # Gas Consumption",
# ylab = "Billion of Cubic Feet")