Combine many instruments into one object
One paradigm involves importing data into a new environment. Then you can use eapply()
to call a function on each object in the environment, much like what lapply()
does for each element of a list. Also like lapply()
, eapply()
returns a list.
Then you can merge all the elements of the list into one object by using do.call()
, which is like having R programmatically type and run a command for you. Instead of typing merge(my_list[[1]], my_list[[2]]], ...)
, you can type do.call(merge, my_list)
.
This exercise is part of the course
Importing and Managing Financial Data in R
Exercise instructions
- Use
eapply()
to callhead()
on each object indata_env
. Assign the result todata_list
. - Use
do.call()
andmerge()
to combine all the elements ofdata_list
into one xts object nameddata_merged
. - Since objects in an environment aren't ordered, there's no guarantee what order the columns of
data_merged
are in. UseOHLC()
to order them, and store the data indata_ohlc
.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# Call head on each object in data_env using eapply
data_list <- ___(data_env, ___)
# Merge all the data_list elements into one xts object
data_merged <- ___(___, data_list)
# Ensure the columns are ordered: open, high, low, close