user3165084
user3165084

Reputation: 91

Create a simple time series

I am trying to create a simple time series but I cant seem to figure out what is going on. I am inputting a simple text tab delimited file as below:

        Date     Time             NOx.Levels
1       02/07/14 00:00:00         37

2       02/07/14 01:00:00         31

3       02/07/14 02:00:00         44

4       02/07/14 03:00:00         25

and I am using the code as follows:

 pollution_data <-read.table(file.choose(),header=T,sep="\t") 
 pollution_data

 dm <- ts(pollution_data, frequency=24, start=c(02/07/2014))
 dm$Date <- as.Date(dm$Date, "%d.%m.%Y")

 require(ggplot2)
 ggplot( data = dm, aes( Date, Visits )) + geom_line() 

I can't seem to get it to plot a simple time series.

Upvotes: 0

Views: 138

Answers (1)

G. Grothendieck
G. Grothendieck

Reputation: 270075

ts is not very good for date/time values. Try the zoo solution below. After that are some other solutions too.

Below index = 1:2 means that the first two columns are the date/time, format= gives the percent codes for the format and tz= specifies the local time zone (which will also cause it to use POSIXct datetimes). autoplot generates a ggplot2 plot.

Lines <- "       Date     Time             NOx.Levels
1       02/07/14 00:00:00         37
2       02/07/14 01:00:00         31
3       02/07/14 02:00:00         44
4       02/07/14 03:00:00         25
"

# 1    
library(zoo)
library(ggplot2)
fmt <- "%m/%d/%y %H:%M:%S"
z <- read.zoo(text = Lines, header = TRUE, index = 1:2, format = fmt, tz = "")
autoplot(z)

(continued after image)

enter image description here

These work too:

# 2
plot(z)

# 3
library(lattice)
xyplot(z)

Another way to do it is:

# 4
library(ggplot2)
DF <- read.table(text = Lines, header = TRUE)
DF$datetime <- as.POSIXct(paste(DF$Date, DF$Time), format = fmt) # fmt defined previously
qplot(datetime, NOx.Levels, data = DF, geom = "line")

If we want to use ts its best to use hours here. We assume the times start at hour 1 and each successive data point is the next hour.

# 5
plot(ts(DF$NOx.Levels), xlab = "hour")

Upvotes: 3

Related Questions