Get startedGet started for free

Encoding your flight data

You're ready to encode your data to an xts object! Remember that flights is a data frame containing four columns of flight data and one column of dates.

To convert to an xts object, you'll need to ensure that your date column is in a time-based format. As you discovered earlier, the date column is currently a character. Once date is saved in a time-based format, you're ready to convert to xts! To do so, you'll use as.xts(), which takes two primary arguments.

First, you'll need to specify the object being converted (in this case, flights). To avoid redundancies, you should generally remove the time-based column from the data when you convert to xts. In this case, you'll remove the fifth column (dates), by specifying [, -5] in your as.xts() call.

Second, you'll need to tell xts how to index your object by specifying the order.by argument. In this case, you want to index your object on the date column.

The flights data frame is preloaded for you.

This exercise is part of the course

Case Study: Analyzing City Time Series Data in R

View Course

Exercise instructions

  • Load the xts package.
  • Use as.Date() to convert the date column in flights from a character to a Date object.
  • Convert your data to an xts object using as.xts(). To do so, you'll need to specify the data being encoded followed by the order.by argument, which generates the time-based index. Save this object as flights_xts.
  • Check the class of flights_xts in your workspace.
  • Examine the first 5 rows of flights_xts.

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

# Load the xts package


# Convert date column to a time-based class
flights$date <- ___(flights$date)

# Convert flights to an xts object using as.xts
flights_xts <- as.xts(___ [ , -___], order.by = ___)

# Check the class of flights_xts


# Examine the first five lines of flights_xts
Edit and Run Code