R for Excel Users: Pivot Tables, VLOOKUPs in R
Want to share your content on Rbloggers? click here if you have a blog, or here if you don't.
New business and financial analysts are finding R
every day. Most of these new userRs (R users) are coming from a nonprogramming background. They have ample domain experience in functions like finance, marketing, and business, but their tool of choice is Excel (or more recently Tableau & PowerBI).
Learning R
can be a major hurdle. You need to learn data structures, algorithms, data science, machine learning, web applications with Shiny
and more to be able to accomplish a basic dashboard. This is a BIG ASK for noncoders. This is the problem I aim to begin solving with the upcoming release of tidyquant
v1.0.0. Read the updated ‘R for Excel Users’ on Business Science.
Let’s demo several of the new Excel features!
Excel in R: Introducing tidyquant
New Features in v1.0.0.9000 (Beta on GitHub)
In tidyquant
version 1.0.0.9000 (still in betamode on GitHub Here, but expected CRAN release of tidyquant v1.0.0 is March 2020), I have added the following features to support new useRs transitioning from an Excel background.
New Features
To make the transition to R easier for Excel Users
✅ NEW Tidyverse Functions – Summarize By Time
???? NEW API Integrations (Implementation scheduled for March)
I’ll showcase a small portion of the new features in this post. Attend Learning Lab 30 (Register Here for Free) for a real business example where I showcase Shiny
and tidyquant
together. You’ll see how the new tidyquant
features streamline development of Financial and Business Shiny
Apps.
Replication Requirements
Please use tidyquant (>= 1.0.0)
. Installation is recommended via GitHub until the official CRAN release (expected in March 2020).
Load the following libraries.
✅ Pivot Tables
The Pivot Table is one of Excel’s most powerful features. Honestly, when I came to R, one of the biggest things I lost was the Pivot Table – A tool used for quickly summarizing data into a digestable table. It’s now in R
with pivot_table()
.
Excel Pivot Table
For those that may have never used the Excel Pivot Table before, the process goes something like this.
 Start with a raw table in “long” format where each row is a unique observation
 Use the Excel Pivot Table dialog to position fields into Columns, Rows, and Summarized Values
 The Pivot Table is returned with the data summarized into columns and rows
Excel Pivot Table is now in R
R Pivot Table
Excel’s Pivot Table now in R
with pivot_table()
. Let’s try it out.
First, let’s get some raw data. The FANG
data set ships with tidyquant
and represents the ouput of the tq_get(c("FB", "AMZN", "NFLX", "GOOG"))
from 2013 to 2016. This is raw OHLCV data with adjusted stock prices downloaded from Yahoo Finance.
We can summarize this information with a Pivot Table using pivot_table(.rows, .columns, .values)
. First, I’ll take a look to see if there are any missing (NA
) values. The only trick is to use a ~
in front of any calculations. All zeros is good.
AMZN  FB  GOOG  NFLX 

0  0  0  0 
Next, I’ll do some financial summarizations. I’d like to take a look at percentage returns by year and quarter. This is easy to do by using stacked functions with the c()
operator on .columns
and .rows
.
symbol  QUARTER(date)  2013  2014  2015  2016 

AMZN  1  0.0356768  0.1547856  0.2060807  0.0680544 
AMZN  2  0.0614656  0.0530919  0.1723923  0.1956892 
AMZN  3  0.1082595  0.0299348  0.1703285  0.1538281 
AMZN  4  0.2425300  0.0223965  0.2979913  0.1038196 
FB  1  0.0864286  0.1010785  0.0480561  0.1162199 
FB  2  0.0254603  0.0745768  0.0502020  0.0153369 
FB  3  1.0245869  0.1613283  0.0344034  0.1233033 
FB  4  0.0838954  0.0192031  0.1507422  0.1065466 
GOOG  1  0.0980851  0.0017401  0.0441873  0.0041923 
GOOG  2  0.0988279  0.0143170  0.0406450  0.0770892 
GOOG  3  0.0134815  0.0091132  0.1659128  0.1116688 
GOOG  4  0.2634837  0.0736798  0.2414403  0.0009578 
NFLX  1  1.0571677  0.0297393  0.1941594  0.0702983 
NFLX  2  0.1571014  0.2081494  0.5901917  0.1345316 
NFLX  3  0.3786783  0.0463327  0.1027844  0.0194477 
NFLX  4  0.1341568  0.2214904  0.0792602  0.2062750 
A few points:
 Collapsing – I just used functions to collapse the daily date by
YEAR()
andQUARTER()
. This essentially creates a new grouping variable that is a part of the date.  Stacking – I stacked multiple grouping operations with the
c()
operator:.rows = c(symbol, ~ QUARTER(date))
 Summarization Details – I added multiple function calls to get the Percentage Change in the
.values
summarization operation. This is allowed as long as the result returns a single value.  Tilde Required – For calculations (e.g.
~ YEAR(date)
), I used the tilde (~
) each time, which is required.  Tilde Not Required – For bare column names with no calculation, a tilde (
~
) is not required.
My Favorite Part of Pivot Tables in R
We can easily switch Pivot Tables to provide different levels of summarization. Now I’ll quickly change to returns by year. Notice I’m using a new summarization function, PCT_CHANGE_FIRSTLAST()
to save me some typing.
symbol  2013  2014  2015  2016 

AMZN  0.5498426  0.2201673  1.1907495  0.1772084 
FB  0.9517858  0.4260647  0.3340983  0.1255136 
GOOG  0.5495473  0.0532416  0.4460024  0.0404130 
NFLX  3.0014129  0.0584587  1.2945491  0.1258640 
✅ VLOOKUP
When I first started learning R, I couldn’t grasp how to merge / join data. It was very frustrating because I was used to Excel’s VLOOKUP function that pulled a value or a column of values as needed.
Excel VLOOKUP
VLOOKUP is an Excel function to lookup and retrieve data from a specific column in table. Here’s how the process works in Excel.
 Start with a Lookup Table. Contains KeyValue pairs.
 Simple Case – Use a VLOOKUP to input a single value and output a single value.
 More Powerful Case – Use a VLOOKUP to add a column to an Excel Table.
Excel VLOOKUP() is now in R
R VLOOKUP
The most popular Excel Reference Function, VLOOKUP
, is now in R as VLOOKUP()
. It’s vectorized, which means we can use VLOOKUP()
inside of dplyr::mutate()
.
Let’s replicate a VLOOKUP in R using the new VLOOKUP()
function. First, let’s create a simple lookup table.
stock  company 

FB  
AMZN  Amazon 
NFLX  Netflix 
GOOG 
Simple VLOOKUP Case
First, let’s mimic the “simple” case where we just want to lookup a Single Value.
So what happened? We supplied the string “AMZN”, and the VLOOKUP()
function new to search the lookup_table
matching the stock
column and returning the company
.
More Powerful VLOOKUP Case
Let’s try the more Powerful Case – pulling in a column of matched lookup values. We can do this by using the mutate()
function from dplyr
. This works because VLOOKUP()
is vectorized.
What I’m Most Excited About Using VLOOKUP for
I actually can’t wait to use VLOOKUP()
in Shiny
apps. There are many times when I want the user to input a variable (a Key), and internally on the Shiny Server convert it to something more useful in a table (a Value). I’ll showcase this technique LIVE in Learning Lab 30 – Shiny + Tidyquant Apps (Register Here for FREE).
✅ Summarizing “IFS” Functions
One of the functions that many Excel Users (including myself) become accustomed to is filtering summations, which I refer to as “IFS” functions. These are very handy at quickly filtering on conditions while aggregating your data.
Excel SumIf’s (and friends)
Excel has SUMIFS()
, COUNTIFS()
, AVERAGEIFS()
, and several more Summarizing “IFS” Functions. Here’s how they work:
 Develop a Condition to summarize: Sum Sales when Region = “East”
 Use one or more Conditioning Column(s) to develop a logical cases (e.g. region = “East”)
 Use a Summarizing Column to aggregate (e.g. SUMIFS(sales))
 Put it together returning a single value: SUMIFS(sales, region, “=East”)
Excel SUMIFS is now in R as SUM_IFS()
R SumIf’s (and friends)
R
now has a full suite of “IFS” functions. We can test them to get the basics.
SUM_IFS()
Summarizing things.
COUNT_IFS()
Counting things.
Used in tidyverse
Let’s use COUNT_IFS()
to count how many times high trade volume occurs in 2015. We can accomplish this shockingly easily by combining summarise()
and the COUNT_IFS()
function.
✅ 100+ New Excel Functions
100+ Excelbased statistical, date/datetime, and financial math functions have been ported to R
. The things I’m most excited about are Business Calendar calculations:

Business Holiday Calendars – Solves a major pain point with business date calculations. Integrations with
lubridate
andtimeDate
have enabled Holiday Date Sequences to automate calculation of Net Work Days and working periods. 
Financial Calculations – I’ve ported
NPV
,IRR
,FV
,PV
,PMT
, andRATE
. Then I realized that there’s an amazing package called FinCal. The plan is to leverageFinCal
going forward.
100+ Excel Functions now in R
Business Calendars: Factoring in Business Holidays made Easy
Businesses rely on their ability to accurately predict revenue. A key driver is whether or not the business is open (shocker!). For a business that’s closed on weekends and standard business holidays, it’s now super easy to calculate something simple like NET_WORKDAYS()
.
Net Working Days Example
When run with just a start and end, it returns the number of days excluding weekends.
But what about holidays? We have a new function called HOLIDAY_SEQUENCE()
to calculate the business holidays between two dates (thanks to timeDate
!).
Now we can simply remove these dates from the Net Workdays calculation. We get 126 days removing standard business holidays.
✅ NEW Tidyverse Functionality
summarise_by_time()
is a new timebased variant of dplyr::summarise()
that allows collapsing timeseries data by “second”, “minute”, “hour”, “day”, “week”, “month”, “quarter”, and “year”.
By Month
Here’s a quick example summarizing by "month"
.
By Year
The benefit is that I can quickly switch periods.
What I’m Most Excited About
I can use summarise_by_time()
in Shiny Apps to make common summarization plots. In fact, I’m teaching it: Learning Lab 30 – Shiny + Tidyquant for Finance Apps (Register Here, It’s Free)
Summarizing by Time in a Shiny App
???? NEW API Integration (Implementation scheduled for March)
Coming Soon – Tingo API
is a popular free and open source for stock prices, cryptocurrencies, and intraday feeds from the IEX (Investors Exchange). I’m planning integration via the riingo
package.
Summary
There’s a ton to learn. So much that I couldn’t possibly go over all of the new features in tidyquant v1.0.0
in this article. And, most importantly, you haven’t seen tidyquant
tackle some real messy business problems.
I have good news. In Learning Lab 30 – Shiny + Tidyquant for Finance Apps (Register Here, It’s Free), I’m going to be tackling some real financial data and showing how we can do really important things like:
 Perform Portfolio Analysis
 Use NEW Excel Features
 Build Shiny Apps with Pivot Tables, VLOOKUPs and SUMIFS.
Experience Shiny + tidyquant
Financial Modeling App with Shiny & tidyquant
Learn how to make a Shiny Finance App using Shiny
+ tidyquant
for financial modeling automation – FOR FREE. Plus, I’ll be showing off my tidyquant 1.0.0
NEW Excel in R Features and how they make it super easy to leverage Shiny
. Registration is a nobrainer. Sign up here. ????
Register for Learning Lab 30 Here
Registration closes March 11th (Day of the event).
Lab 30 – Shiny + Tidyquant starts in…
Rbloggers.com offers daily email updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/datascience job.
Want to share your content on Rbloggers? click here if you have a blog, or here if you don't.