Get startedGet started for free

Fill missing values by trading day

The previous exercise carried the last observation of the prior day forward into the first observation of the following day. This exercise will show you how to fill missing values by trading day, without using the prior day's final value.

You will use the same split-lapply-rbind paradigm from the Introduction to xts and zoo course. For reference, the pattern is below.

x_split <- split(x, f = "months")
x_list <- lapply(x_split, cummax)
x_list_rbind <- do.call(rbind, x_list)

Recall that the do.call(rbind, ...) syntax allows you to pass a list of objects to rbind() instead of having to type all their names.

Your workspace has a trade_day object that contains the regular series from the previous exercise, but without any NA filled in.

This exercise is part of the course

Importing and Managing Financial Data in R

View Course

Exercise instructions

  • Create a daily_list object by using split() to put the trade_day data into a list of data for each day.
  • Now use lapply() to fill the NA for each day's data in the daily_list list.
  • Finally, use do.call() and rbind() to convert daily_filled to a single xts object named filled_by_trade_day.

Hands-on interactive exercise

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

# Split trade_day into days
daily_list <- split(___ , f = "___")

# Use lapply to call na.locf for each day in daily_list
daily_filled <- lapply(___, FUN = ___)

# Use do.call to rbind the results
filled_by_trade_day <- do.call(rbind, ___)
Edit and Run Code