Pivoting from wide to long
For pivoting from wide to long, we use
The most important arguments to the function are
values_to. You can probably guess at their relationship to the arguments to
colsspecifies the columns that we want to take from wide to long.
names_tospecifies a name for the column in our long data frame that will hold the column names from the wide data frame.
values_tospecifies a name for the column in our long data frame that will hold the values in the cells of the wide data frame.
In our example:
- We want to take the columns holding the returns for each ticker from wide to long, so we want
colsto take all the columns except date. We can do that by specifying
cols = -date
- We want the names of the
colsto be held in a long variable called
tickers, so we specify
names_to = "ticker". Note that
"ticker"here is a string variable.
- We want to hold the values from our wide columns in a long column called
"returns"so we specify
values_to = "returns". Again note the string variable.
Here’s what that looks like:
pivot_longer(cols = -date, names_to = ‘ticker’, values_to= ‘returns’) %>%
kable_styling(full_width = FALSE, position = ‘center’) %>%
scroll_box(width = ‘800px’, height = ‘300px’)
And you can see that we’ve recovered our original long form dataframe.
One example where you’d be forced to pivot you long returns data frame to wide would be to calculate a correlation matrix:
pivot_wider(names_from = ticker, values_from = returns) %>%
cor(use = “pairwise.complete.obs”, method=’pearson’) %>%
kable_styling(position = ‘center’) %>%
scroll_box(width = ‘800px’, height = ‘300px’)
You can see that we’ve also used the
select function from
dplyr to drop the date column before passing the wide data frame of returns to the
cor function for calculating the correlation matrix.
Plotting long format data
When you want to plot more than one variable on a single chart, long data is most definitely your friend:
ggplot(aes(x = date, y = returns, colour = ticker)) +
ggplot(aes(x = date, y = returns)) +
Using wide-format data to make a similar plot would require repeated calls to
geom_line for each variable, which is quite painstaking and brittle.
For example, if something changes upstream, such as the addition of a new ticker to the data set, your code will also need to change in order to plot it. That’s not the case if we use long data with a column holding the ticker variable.
Visit Robot Wealth website to read the full article and watch the instructional video: https://robotwealth.com/working-with-tidy-financial-data-in-tidyr/
Disclosure: Interactive Brokers
Information posted on IBKR Traders’ Insight that is provided by third-parties and not by Interactive Brokers does NOT constitute a recommendation by Interactive Brokers that you should contract for the services of that third party. Third-party participants who contribute to IBKR Traders’ Insight are independent of Interactive Brokers and Interactive Brokers does not make any representations or warranties concerning the services offered, their past or future performance, or the accuracy of the information provided by the third party. Past performance is no guarantee of future results.
This material is from Robot Wealth and is being posted with permission from Robot Wealth. The views expressed in this material are solely those of the author and/or Robot Wealth and IBKR is not endorsing or recommending any investment or trading discussed in the material. This material is not and should not be construed as an offer to sell or the solicitation of an offer to buy any security. To the extent that this material discusses general market activity, industry or sector trends or other broad based economic or political conditions, it should not be construed as research or investment advice. To the extent that it includes references to specific securities, commodities, currencies, or other instruments, those references do not constitute a recommendation to buy, sell or hold such security. This material does not and is not intended to take into account the particular financial conditions, investment objectives or requirements of individual customers. Before acting on this material, you should consider whether it is suitable for your particular circumstances and, as necessary, seek professional advice.
In accordance with EU regulation: The statements in this document shall not be considered as an objective or independent explanation of the matters. Please note that this document (a) has not been prepared in accordance with legal requirements designed to promote the independence of investment research, and (b) is not subject to any prohibition on dealing ahead of the dissemination or publication of investment research.