<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Anita Owens on Medium]]></title>
        <description><![CDATA[Stories by Anita Owens on Medium]]></description>
        <link>https://medium.com/@anitaowens?source=rss-9790253b531b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*mFTKW_ek0rCAU3ITntwhmQ.jpeg</url>
            <title>Stories by Anita Owens on Medium</title>
            <link>https://medium.com/@anitaowens?source=rss-9790253b531b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 07:20:46 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@anitaowens/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[If You’re Switching Into Data in 2026, Here’s What You’re Competing Against]]></title>
            <link>https://anitaowens.medium.com/the-data-job-market-shift-nobodys-telling-you-about-ab356c534926?source=rss-9790253b531b------2</link>
            <guid isPermaLink="false">https://medium.com/p/ab356c534926</guid>
            <category><![CDATA[analytics-engineering]]></category>
            <category><![CDATA[hiring]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[career-change]]></category>
            <dc:creator><![CDATA[Anita Owens]]></dc:creator>
            <pubDate>Sat, 03 Jan 2026 13:50:05 GMT</pubDate>
            <atom:updated>2026-01-06T09:31:43.717Z</atom:updated>
            <content:encoded><![CDATA[<p><em>The career change playbook that worked a few short years ago no longer applies</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Dc9gws7SDTGrrrBLbCTXnQ.jpeg" /><figcaption>Image by Author</figcaption></figure><p>In 2015, as an American living in Stockholm whose degrees didn’t translate, I needed to figure out how to enter the Swedish job market. I enrolled in a 1.5-year data strategy program, betting that data skills would <em>future-proof</em> my career. It was a long, hard road, but I learned the technical skills, made the transition, and found a profession I genuinely enjoy.</p><p>What worked for me then doesn’t work now. The market has fundamentally changed in ways many educational programs haven’t caught up with. I’ve been on both sides of this shift: teaching in data programs and hiring for analytics roles. I keep seeing the same questions: “Should I do a bootcamp?” “Is the Google certificate worth it?” “Can I transition without a technical background?”</p><p>Before you invest time and money into this career path, you need to understand what actually happened to the data job market because the programs selling you on this transition are still using playbooks from 2018.</p><h3><strong>The Golden Window: 2012–2019</strong></h3><p><a href="https://hbr.org/2012/10/data-scientist-the-sexiest-job-of-the-21st-century">Harvard Business Review </a>famously declared Data Scientist the “sexiest job of the 21st century” back in 2012. Two things happened: people started asking “What is a Data Scientist?” and “How do I become one?” In response, companies started hiring data professionals to build out data analytics departments.</p><p>Many hired “data scientists” as their first data hire when there was no infrastructure in place. These early hires had to be generalists who built their own data pipelines, did analysis, and created dashboards all at once.</p><p>The technical bar? SQL, Excel, and Python for Data Science. The competition was manageable. Short-term programs or certificates could actually get you in the door. This was the golden window, and if you entered the field during this period, you got in relatively easily compared to today.</p><h3><strong>The Contraction: 2020-Present</strong></h3><p>Then COVID happened. Many data professionals found themselves laid off as companies cut roles that weren’t essential for operations. Meanwhile, people flocked to schools to ride out economic uncertainty, particularly those in service roles looking to pivot.</p><p>With an overflow of data professionals to choose from, competition exploded. Bootcamp grads, laid-off tech workers, STEM degree holders, and recent graduates all flooded the market simultaneously.</p><p>But here’s what made it worse: the roles themselves became more technical. Analytics Engineer and Data Engineer emerged as distinct roles with higher technical bars. The entry-level analyst positions that once served as stepping stones started disappearing. In effect, the bar to entry shot up just as more people were trying to enter.</p><h3><strong>What This Looked Like From the Hiring Side</strong></h3><p>When I was hiring for an analytics engineer position, we received hundreds of applicants. The stack included:</p><ul><li>Physics PhDs pivoting to data</li><li>Economics graduates with statistics backgrounds</li><li>Computer Science graduates</li><li>Experienced analysts from companies doing layoffs</li></ul><p>What made someone stand out wasn’t credentials or degrees. It was demonstrable technical depth: evidence of real-world experience, proof they could solve business problems now, not potential they might develop in six months.</p><p>We needed people who could navigate ambiguous stakeholder requirements, debug broken data pipelines, and communicate technical constraints to non-technical stakeholders.</p><p>But it went further than execution. We were looking for people who understood analytics well enough to act as partners in business decision-making, who could challenge assumptions and help the business ask better questions in the first place. This was more than just implementing ticket requests.</p><p>This is the fundamental disconnect between what employers need and what most educational programs offer.</p><h3><strong>Your Next Best Move</strong></h3><p>Before you invest in any bootcamp or certificate program, understand what you’re actually competing against. The market isn’t broken — it’s evolved and it’s changing. And most educational programs are still selling you the pre-2020 version of this career path.</p><h3><strong>Here’s what to do right now:</strong></h3><ol><li>Search “junior data analyst” or “analytics engineer” jobs in your area on LinkedIn</li><li>Look at who’s actually in those roles (check their backgrounds on LinkedIn)</li><li>Count how many applicants each posting has</li><li>Ask yourself honestly: “Can I compete against physics PhDs, CS graduates, and experienced analysts and engineers?”</li></ol><p>That reality check will tell you more than any bootcamp marketing material.</p><p>The shift is real. The competition is intense. But there <strong>ARE</strong> paths that work in 2026, but they just look different than the ones programs are selling you.</p><p>Want the full analysis? I wrote the comprehensive guide I wish had existed: what roles actually require, realistic timelines, paths that work, and questions to ask before spending money.</p><blockquote>👉🏾 <strong>Read the full guide on Substack:</strong> <a href="https://anitaowens.substack.com/p/before-you-buy-that-data-analytics">Before You Buy That Data Analytics Certificate: What the Data Job Market Actually Looks Like in 2026</a></blockquote><h4>References</h4><p>Davenport, Thomas H., and D.J. Patil. “Data Scientist: The Sexiest Job of the 21st Century.” <em>Harvard Business Review</em> 90, no. 10 (October 2012): 70–76. <a href="https://hbr.org/2012/10/data-scientist-the-sexiest-job-of-the-21st-century">https://hbr.org/2012/10/data-scientist-the-sexiest-job-of-the-21st-century.</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ab356c534926" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to simulate sales data in Python]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://anitaowens.medium.com/how-to-simulate-sales-data-in-python-67c0dd4dae56?source=rss-9790253b531b------2"><img src="https://cdn-images-1.medium.com/max/2600/0*Cp0OAaE-aZnGXEkw" width="6048"></a></p><p class="medium-feed-snippet">Stretch your data analysis skills by creating your own datasets</p><p class="medium-feed-link"><a href="https://anitaowens.medium.com/how-to-simulate-sales-data-in-python-67c0dd4dae56?source=rss-9790253b531b------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://anitaowens.medium.com/how-to-simulate-sales-data-in-python-67c0dd4dae56?source=rss-9790253b531b------2</link>
            <guid isPermaLink="false">https://medium.com/p/67c0dd4dae56</guid>
            <category><![CDATA[synthetic-data]]></category>
            <category><![CDATA[marketing-analytics]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Anita Owens]]></dc:creator>
            <pubDate>Sat, 31 Dec 2022 19:17:46 GMT</pubDate>
            <atom:updated>2024-03-01T21:58:41.013Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[How to calculate marketing impact when you can’t A/B test]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/geekculture/how-to-calculate-marketing-impact-when-you-cant-a-b-test-bc64105362a4?source=rss-9790253b531b------2"><img src="https://cdn-images-1.medium.com/max/2600/0*85OPhPp5TR-ujffN" width="4500"></a></p><p class="medium-feed-snippet">An example of before-and-after analysis in R</p><p class="medium-feed-link"><a href="https://medium.com/geekculture/how-to-calculate-marketing-impact-when-you-cant-a-b-test-bc64105362a4?source=rss-9790253b531b------2">Continue reading on Geek Culture »</a></p></div>]]></description>
            <link>https://medium.com/geekculture/how-to-calculate-marketing-impact-when-you-cant-a-b-test-bc64105362a4?source=rss-9790253b531b------2</link>
            <guid isPermaLink="false">https://medium.com/p/bc64105362a4</guid>
            <category><![CDATA[r-programming]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[marketing-analytics]]></category>
            <category><![CDATA[a-b-testing]]></category>
            <dc:creator><![CDATA[Anita Owens]]></dc:creator>
            <pubDate>Wed, 28 Sep 2022 18:01:24 GMT</pubDate>
            <atom:updated>2024-03-01T22:00:15.348Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[How to build a sales forecast in Python]]></title>
            <link>https://anitaowens.medium.com/how-to-build-a-sales-forecast-in-python-5a1bc05326be?source=rss-9790253b531b------2</link>
            <guid isPermaLink="false">https://medium.com/p/5a1bc05326be</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[forecasting]]></category>
            <category><![CDATA[linear-regression]]></category>
            <dc:creator><![CDATA[Anita Owens]]></dc:creator>
            <pubDate>Thu, 28 Jul 2022 06:45:05 GMT</pubDate>
            <atom:updated>2024-03-01T22:01:25.377Z</atom:updated>
            <content:encoded><![CDATA[<p>Does shelf location impact sales? A step-by-step forecasting guide with linear regression.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*yXWvSHRGz_z6DA0u" /><figcaption>Photo by <a href="https://unsplash.com/@norevisions?utm_source=medium&amp;utm_medium=referral">No Revisions</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In an earlier <a href="https://medium.com/geekculture/how-to-build-a-sales-forecast-in-r-dafabb03a076">article</a>, I built a forecast model to answer the question of whether grocery store shelf location impacts sales using linear regression in R. In this article, I will replicate the forecast exercise in Python using pandas, numpy, and statsmodels. This dataset is from Chapter 10 of <em>Wayne L. Winston’s Marketing Analytics: Data-Driven Techniques with Microsoft Excel.</em></p><p>Our Oreos dataset has 3 columns:</p><ol><li>Observation number</li><li>Height in feet</li><li>Sales</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/390/1*DwVZkBQRJ4SgrO9ivJkwTA.png" /><figcaption>Preview of our dataset. Image by author.</figcaption></figure><h3>Data Exploration</h3><p>Before we step into data modeling, it’s a good idea to visualize our data to get a sense for it.</p><pre>#Boxplot with striplot - each individual data point super-imposed on boxplot</pre><pre>sns.boxplot(data=df, x=&quot;Heightinfeet&quot;, y=&quot;Sales&quot;)<br>sns.stripplot(data=df, x=&quot;Heightinfeet&quot;, y=&quot;Sales&quot;, color = &#39;black&#39;, size = 8, alpha = 0.3)<br>plt.xlabel(&quot;Shelf Height in Feet&quot;, size = 12)<br>plt.ylabel(&quot;Cookie Sales&quot;, size = 12)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/515/1*x2dHe-meV65KolVYOzp0MQ.png" /><figcaption>Sales by shelf height. It’s clear that sales are higher when shelf height is six (6) feet. Image by author.</figcaption></figure><p>How about some summary statistics.</p><pre>#What are average sales overall?</pre><pre>round(df[&#39;Sales&#39;].mean(),1)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/643/1*B5kuYE51TILq4AJECkHB1A.png" /><figcaption>Average sales overall. Image by author.</figcaption></figure><pre>#What is the average &amp; total sales by shelf location?</pre><pre>#Group by heightinfeet and take mean, median, and sum of sales</pre><pre>df.groupby(&#39;Heightinfeet&#39;).agg({&#39;Sales&#39;: [&#39;mean&#39;, &#39;median&#39;, &#39;sum&#39;]})</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/272/1*-u0GhPEUavmyYMIi7eVlag.png" /><figcaption>Average sales and sum of sales by height. Image by author.</figcaption></figure><p><strong>Some important insights we uncovered during the data exploration step include:</strong></p><p>Overall sales over the entire dataset is 44 on average.<br>Higher sales when shelf height is at 6 feet. On average 61.<br>Lower sales when shelf height as at 5 feet. On average 44.50</p><h3>Forecast Modeling</h3><p>We will build a forecast model using linear regression with the Python statsmodels package and the ols() function.</p><p>We only have one (1) dependent variable <em>(Sales) </em>and one (1) independent variable <em>(Heightinfeet)</em>. We will assume that <em>Sale</em>s are in number of units. We will treat <em>Heightinfeet</em> as a categorical variable. This will affect how we interpret the output of our regression model. We ignore the first column for building our model.</p><pre>#Convert Heightinfeet from numeric to categorical object</pre><pre>df[&#39;Heightinfeet&#39;] = df[&#39;Heightinfeet&#39;].astype(&#39;category&#39;)<br></pre><pre># Create the model object</pre><pre>forecast_model = ols(&quot;Sales ~ Heightinfeet&quot;, data=df)<br></pre><pre># Fit the model</pre><pre>forecast_model = forecast_model.fit()<br></pre><pre># Print the summary of the fitted model</pre><pre>print(forecast_model.summary())</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/874/1*Rgrp-klsHU7lHLV1S77mYg.png" /><figcaption>Output of linear regression model. Image by author.</figcaption></figure><h3>Interpreting the OLS (least squares) output</h3><p><em>Going from left to right starting with the coefficients</em></p><p><strong>Coefficients (coef)</strong></p><p>A positive coefficient indicates that as the value of the independent variable increases (height), the mean of the dependent variable (sales) also tends to increase.</p><p><em>Intercept or Constant(B0)</em></p><p>The intercept is the value of the dependent variable (y) when all of the independent variables (x) are zero. In this case, since we have only one categorical variable as a predictor, the intercept is the mean value of Oreo sales at a shelf height of five feet (the reference group on the intercept).</p><p><em>Heightinfeet6(B1), Heightinfeet7(B2)</em></p><p>At 5 feet sales are 23.75. Now we interpret 6 and 7 feet in relation to the 5 feet shelf location.</p><p>At 6 feet sales increases by a whopping 36 units, but at 7 feet, sales increase by only 16 units in relation to 5 feet.</p><p>Overall, 6 feet is a better location for our Oreos if we want to optimize for sales.</p><p><strong>Standard error (std err)</strong></p><p>Standard error of estimated coefficient. A measure of how precise the slope has been estimated. The lower the better.</p><p><strong>t statistic (t)</strong></p><p>We want to know if the t-statistic falls within the rejection region. One of three (3) approaches of hypothesis testing using regression output. In regression, hypothesis testing is needed to test if the <strong>estimates</strong> that we get from the regression model (<em>which is based on a sample of data)</em> are true.</p><p><strong>P-values (P&gt;|t|)</strong></p><p>Low p-values are good. The p-values are &lt;.05 for both independent variables. (Heightinfeet[T.6] &amp; Heightinfeet[T.7]). This implies that we reject the null hypothesis (that the beta coefficients are zero). The last of the three (3) approaches of hypothesis testing using regression output.</p><p><strong>Confidence Intervals [0.025 0.975]</strong></p><p>This informs us if the beta coefficient falls within the confidence interval range. For example, at 5 feet sales are 23.75, but could be within the range of 16.8 to 30.7. The second of three (3) approaches of hypothesis testing using regression output.</p><p><em>Starting from the top right of the regression output</em></p><p><strong>R-squared/Coefficient of determination</strong></p><p>The r-squared value of 0.886 indicates that 89% of the variation in sales is explained by shelf height. The remaining variation of 11% goes unexplained. A goodness of fit measure for regression output.</p><p><strong>Adj. R-squared</strong></p><p>Controls for the number of independent variables (x) in a model. Quite useful when comparing multiple regressions models against one another.</p><p><strong>F-statistic</strong></p><p>The f-statistic of 34.99 tells us whether the model is significant or not significant. The model is significant if any of the coefficients are <strong>non-zero</strong>, which in this case, is true.</p><h4><em>How do we write our equation if we want to use this linear model to forecast sales?</em></h4><p>Our equation:</p><pre>Sales = 23.75 + 36.25(6 feet) + 16(7 feet)</pre><p>Luckily, for us we can use Python to do the math for us at scale to predict future sales.</p><h3>Build Forecast Model</h3><p>Let’s go ahead and build our forecast model. We need to create a new DataFrame to hold our future forecast.</p><pre># Create explanatory_data</pre><pre>explanatory_data = df</pre><pre>print(explanatory_data)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/370/1*9PxfQILEwGI7OcM1K0iImw.png" /><figcaption>The explanatory DataFrame is a copy of our original dataFrame. Image by author.</figcaption></figure><p>We will use the <strong>predict</strong> function to make predictions on this dataset and save results to a new DataFrame called prediction_data.</p><pre>#Use forecast_model to predict future sales using predict function</pre><pre>future_sales = forecast_model.predict(explanatory_data)<br></pre><pre># Create prediction_data. Future_sales has been added as a column to the explanatory data DataFrame</pre><pre>prediction_data = explanatory_data.assign(</pre><pre>future_sales = future_sales)<br></pre><pre>print(prediction_data)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/506/1*XiyzKHCmB5hfCn_w0nrrrA.png" /><figcaption>Explanatory data with new column that holds the future predictions. Image by author.</figcaption></figure><p>Let’s plot the sales with the predictions using our new prediction_data DataFrame.</p><pre>#Plot predictions, but first convert Heightinfeet back to numeric object</pre><pre>df[&#39;Heightinfeet&#39;] = pd.to_numeric(df[&#39;Heightinfeet&#39;])<br></pre><pre># Plot first the data for our original dataset</pre><pre>fig = plt.figure()</pre><pre>sns.scatterplot(x=&quot;Heightinfeet&quot;,</pre><pre>y=&quot;Sales&quot;,</pre><pre>data=df,</pre><pre>color = &quot;darkgrey&quot;,</pre><pre>marker = &quot;o&quot;)<br></pre><pre># Add a scatter plot layer</pre><pre>sns.scatterplot(x=&quot;Heightinfeet&quot;,</pre><pre>y=&quot;future_sales&quot;,</pre><pre>data=prediction_data,</pre><pre>color = &quot;red&quot;,</pre><pre>marker = &quot;s&quot;)<br></pre><pre># Add title</pre><pre>plt.title(&#39;Forecasted Sales marked with red square&#39;)<br></pre><pre>#Add x-label</pre><pre>plt.xlabel(&#39;Shelf Height&#39;)<br></pre><pre># Show the plot</pre><pre>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*QIJPuBiJpe2iW0jpMqGx1w.png" /><figcaption>Actual sales in grey. Forecasted sales in red. Image by author.</figcaption></figure><p>Practically speaking, if we wanted to forecast sales manually at each shelf height, we would calculate it like the following:</p><pre>sales_at_seven_feet = 23.75 + 36.25*(0) + 16*(1)</pre><pre>sales_at_six_feet = 23.75 + 36.25*(1) + 16*(0)</pre><pre>sales_at_five_feet = 23.75 + 36.25*(0) + 16*(0)</pre><h3>Sales Forecast Model at All Shelf Heights</h3><p>Let’s create a forecast model for all shelf heights.</p><pre>#Create a forecast table where we group by heightinfeet and take mean and sum of sales</pre><pre>forecast_table = prediction_data.groupby(&#39;Heightinfeet&#39;, as_index=False).agg(</pre><pre>#get average forecasted sales<br>forecasted_avg_sales = (&#39;future_sales&#39;, &#39;mean&#39;),</pre><pre>#get total forecasted sales<br>forecasted_total_sales = (&#39;future_sales&#39;,sum)<br>).round(2) #Round numbers after the final aggregation</pre><pre>#Make a nice looking Plotly table<br>fig = go.Figure(data=[go.Table(<br>    header=dict(values=list(forecast_table.columns),<br>                fill_color=&#39;#A5D8DD&#39;,<br>                align=&#39;center&#39;),<br>    cells=dict(values=[forecast_table.Heightinfeet, forecast_table.forecasted_avg_sales, forecast_table.forecasted_total_sales],<br>               fill_color=&#39;#F1F1F1&#39;,<br>               align=&#39;center&#39;))<br>])</pre><pre>fig.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/615/1*ERvIwyqI_7dF2k4mymqebQ.png" /><figcaption>Forecast model. Image by author.</figcaption></figure><p>Now we have a full forecast model. Conceptually, let’s walk through what our analysis and forecast model means for the business.</p><p><strong>7 feet — 5 feet</strong></p><blockquote>Putting Oreos at 7 feet relative to 5 feet <strong>increases</strong> sales by 16</blockquote><p><strong>6 feet — 5 feet</strong></p><blockquote>Putting Oreos at 6 feet relative to 5 feet <strong>increases</strong> sales by 36</blockquote><p><strong>7 feet — 6 feet</strong></p><blockquote>Putting Oreos at 7 feet relative to 6 feet <strong>decreases</strong> sales by 20</blockquote><p><strong>NOTE:</strong> If you need to evaluate the point forecast accuracy, you should test your forecast model on data that it has not seen before by splitting the data into <strong>training </strong>and <strong>test</strong> sets. Train the model on the training data and test the model on the test data <em>(e.g. the most recent data)</em>. Then evaluate forecast based on your performance metric of choice e.g. mean squared error (MSE), mean absolute error (MAE), mean absolute percent error (MAPE) etc.</p><h3>Final Summary</h3><p><strong><em>Business Question: </em></strong>Does shelf location impact sales?</p><p><strong><em>Business Answer:</em></strong> Yes, shelf location impacts sales. If we want to maximize sales, then placing our product at 6 feet gives us the best sales. We will sell on average 60 units vs (24 at 5 feet and 40 at 7 feet.) If we place our product at 6 feet, we can expect to sell approximately 240 total units.</p><p><strong><em>Why does this forecasting method (mean method) work?:</em></strong> Taking the average is very effective as a forecasting tool as all future values are equal to the mean of the historical data.</p><p>The dataset and full code <em>(including performance evaluation metrics)</em> can be found on <a href="https://github.com/anita-owens/Forecasting-in-Python/blob/master/How%20to%20build%20a%20sales%20forecast%20in%20Python.ipynb">Github.</a></p><h3>Tip</h3><p>When you have one categorical variable in a linear regression model, the coefficients of the model are the means of each category. You can get the means by removing the intercept from the model as illustrated below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/827/1*BvFtnz36dmd4EIiuUwHKug.png" /><figcaption>Linear regression model with the intercept removed. Image by author.</figcaption></figure><h3>References</h3><p>[1]. Winston, W. L. (2014) Marketing Analytics: Data-driven techniques with Microsoft Excel. Wiley. Pg 225-234.</p><p>[2]. Hyndman, R.J., &amp; Athanasopoulos, G. (2021) Forecasting: principles and practice, 3rd edition, OTexts: Melbourne, Australia. <a href="https://otexts.com/fpp3/">OTexts.com/fpp3</a>. Accessed on 15–07–2022.</p><p>[3]. Chatterjee, S., &amp; Hadi, A. S. (2012) Regression analysis by example. Wiley. Pg 37.</p><p>[4]. Borle, S., Linear Regression for Business [MOOC]. Coursera. <a href="https://www.coursera.org/learn/linear-regression-business-statistics">https://www.coursera.org/learn/linear-regression-business-statistics</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5a1bc05326be" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to use correlation analysis to improve marketing performance in Python & R]]></title>
            <link>https://medium.com/geekculture/how-to-use-correlation-analysis-to-improve-marketing-performance-in-python-r-156e80187d74?source=rss-9790253b531b------2</link>
            <guid isPermaLink="false">https://medium.com/p/156e80187d74</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[marketing-analytics]]></category>
            <category><![CDATA[forecasting]]></category>
            <category><![CDATA[r-programming]]></category>
            <dc:creator><![CDATA[Anita Owens]]></dc:creator>
            <pubDate>Tue, 21 Jun 2022 04:03:12 GMT</pubDate>
            <atom:updated>2024-03-02T08:18:03.487Z</atom:updated>
            <content:encoded><![CDATA[<p>What are the key drivers of sales?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*i1IVZ_kByM1QKJwg" /><figcaption>Photo by <a href="https://unsplash.com/@nguyendhn?utm_source=medium&amp;utm_medium=referral">Nguyen Dang Hoang Nhu</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Why correlation?</h3><p>It is important to understand what drives relationships. For example, if you want to determine how marketing performance impact your sales numbers you have to account for all factors that can explain your sales numbers. This could include factors like:</p><ol><li>marketing channels</li><li>season</li><li>geographic location</li><li>etc.</li></ol><p>Correlation is a great exploratory tool that can sometimes reveal interesting patterns in your data. Most importantly, once you get the hang of it, it is really easy to add to your analysis toolkit.</p><h3>What is correlation?</h3><p>A correlation is a statistic that quantifies the strength between 2 variables. The statistic is called the correlation coefficient denoted as <em>r</em>.</p><p>The correlation coefficient or <em>r </em>is a number between +1 and -1 and is calculated so as to represent the linear relationship between two variables. An <em>r</em> close to 1 indicates a strong relationship between the variables while an <em>r</em> close to 0 indicates a weak relationship.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7f9UKkmkNHAzDkeMPT2xMg.png" /><figcaption>Correlation examples. Image by author.</figcaption></figure><p>A positive or negative sign indicates the direction of the relationship. A positive <em>r</em> indicates a positive relationship and a negative<em> r </em>a negative relationship. Also, we can plot the statistic in a correlation plot or matrix <em>(which we will do shortly)</em>.</p><p>Let’s cover three (3) common correlation methods:</p><ol><li>Pearson method — correlation is the default for linear relationships and assumes your data is normally distributed. It is sensitive to outliers and skewed data.</li><li>Spearman method — for non-normal populations. Checks for rank or ordered relationships.</li><li>Kendall method — for when you have a small dataset and many tied or rank relationships.</li></ol><p>Your choice of correlation method should be driven by the underlying distribution of your data.</p><h3>How to interpret correlation</h3><p>Correlation thresholds using <a href="https://en.wikipedia.org/wiki/Effect_size#Types">Jacob Cohen’s Rule of Thumb</a> which is often used in the behavioral sciences to interpret the effect size:</p><p>r &gt;= 0.5 large or strong association<br>r = 0.3 medium association<br>r = 0.1 small or weak association</p><p>If the underlying data distribution is not normal, then you could transform (e.g. logarithm, Box-Cox, etc.) your variables before attempting to apply these thresholds.</p><h3>What’s an acceptable correlation?</h3><p>Even if the correlation coefficient is <strong>at</strong> or <strong>near</strong> zero, that doesn’t mean no relationship exists. It’s just that relationship isn’t linear, but there could be other relationships which is why it’s important to visualize your variables beforehand.</p><h3>Exploratory Visualization and Correlation Analysis</h3><p>We will be using this marketing dataset that is available on <a href="https://www.kaggle.com/datasets/veer06b/marrket-mix-dataset">Kaggle</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/820/1*QzGMhjShmpROWDYo95-OOg.png" /><figcaption>Marketing Mix dataset from Kaggle. Image by author.</figcaption></figure><p>The data contains the sales data for two consecutive years of a product of a non-specified brand. Each row contains the Volume of Sales for a week and includes additional information or various promotion methods for that product for each week. Let’s inspect the dataset.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/499/1*iBYbF3EWjRVESwNCyNZSPQ.png" /><figcaption>Inspect DataFrame in Python. Image by author.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/713/1*7DlF_S-3Q3QGe9dOknNlnA.png" /><figcaption>Inspect dataframe in R. Image by author.</figcaption></figure><p>Take notice, we have some null values on the Radio, NewspaperInserts, and Website_Campaign columns.</p><p>Let’s do some exploratory data visualization of our dataset.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b5FFPxWppYpcHK-2tfcN_A.png" /><figcaption>EDA in R. Image by author.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/503/1*WUztgiSGPBBZxShF4QIG7Q.png" /><figcaption>EDA in Python. Image by author.</figcaption></figure><p><strong>What can we tell from the exploratory data visualization?</strong></p><blockquote>Sales appear to be relatively normal with perhaps a bit of right skew, but not enough to be particularly worrying.</blockquote><blockquote>Higher sales when the base price is low. Less sales when base price is high.</blockquote><blockquote>Stout seems to have a negative impact on sales. Not sure what stout refers to as it was not included in the data dictionary and the data source is anonymous.</blockquote><blockquote>InStore appears to have a positive impact on sales.</blockquote><blockquote>Both Radio &amp; TV impact inconclusive. More sales when radio &amp; tv spending is going on, but not necessarily always the case.</blockquote><blockquote>Newspaper insert doesn’t appear to have any significant impact on sales.</blockquote><blockquote>Website Campaign appears to have more sales when there is Twitter engagement, but it doesn’t appear to be significantly different when there is no website campaign going on.</blockquote><p>Next, let’s create our correlation plot.</p><pre>#Python<br>corr = df.corr()<br>corr.style.background_gradient(cmap=&#39;RdYlGn&#39;)</pre><pre>#R<br>df %&gt;% <br> select_if(is.numeric) %&gt;% <br>  cor() %&gt;% <br>    corrplot(type = &quot;upper&quot;, addCoef.col = &quot;black&quot;, diag=FALSE)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/604/1*b6P7336abGJ6GCSNhpefxQ.png" /><figcaption>Correlation matrix with heatmap in Python. Image by author.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ToFgxM4NBtNji-tO-h4qBg.png" /><figcaption>Correlation matrix with heatmap in R with corrplot package. Image by author.</figcaption></figure><p>We have the correlation coefficients in each box. Positive correlations are in blue. Negative correlations are in red.</p><p><strong>Summary of correlations:</strong></p><p>Instore and discount both have a medium positive correlation to NewVolSales.</p><p>Radio and TV have a weak positive correlation to NewVolSales.</p><p>Price has a strong negative correlation to NewVolSales.</p><p>Last, but not least, Stout has a medium negative correlation to NewVolSales</p><blockquote><strong>NOTE</strong>: The coefficient of determination is our correlation coefficient squared. It is the proportion of the variance in the y (dependent) variable that is predictable from our x (independent) variable.</blockquote><h3>Correlation and it’s relationship to regression</h3><p>Let’s review how correlation and regression are related by reviewing just 2 variables (NewVolSales and Discount).</p><p>The correlation coefficient of NewVolSales and Discount ads is 0.42 (rounded to 2 decimal places).</p><pre>#Python<br>round(df[&#39;NewVolSales&#39;].corr(df[&#39;Discount&#39;]),2)<br>0.42</pre><pre>#R<br>round(cor(df$NewVolSales, df$Discount),2)<br>0.42</pre><p>If we model this in a linear regression model and extract the r-squared, the result is 0.18. (rounded to 2 decimal places).</p><pre># Python<br><br>sales_vs_discount = ols(&quot;NewVolSales ~ Discount&quot;, data=df)</pre><pre>sales_vs_discount = sales_vs_discount.fit()</pre><pre>print(sales_vs_discount.summary())<br></pre><pre># R</pre><pre>linear_model &lt;- lm(NewVolSales ~ Discount, data = df)</pre><pre>summary(linear_model)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*62tIityrjvezzA5Ckmj_uA.gif" /><figcaption>Output of linear model for NewVolSales as explained by Discount. Python and R output. Image by author.</figcaption></figure><p>If we square the correlation coefficient of 0.42, we will get our r-squared 0.180. In effect, the correlation coefficient squared is the r-squared.</p><h3>Testing for Significance</h3><p>Let’s test significance of all the variables in our dataset by using a linear regression model on the entire dataset.</p><pre># Python (Full Model)<br>mkmix_model = ols(&quot;NewVolSales ~ Base_Price + Radio + InStore + NewspaperInserts + Discount + TV + Stout + Website_Campaign&quot;, data=df)</pre><pre>Fit the model<br>mkmix_model = mkmix_model.fit()</pre><pre>Print the summary of the fitted model<br>print(mkmix_model.summary())</pre><pre># R (Full Model)<br>model_spec_lm &lt;- linear_reg() %&gt;%<br>    set_engine(&#39;lm&#39;) %&gt;% <br>    set_mode(&#39;regression&#39;)</pre><pre>mkmix_model &lt;- model_spec_lm %&gt;%<br>    fit(NewVolSales ~ Base_Price + Radio + InStore + factor(NewspaperInserts) + Discount + TV + Stout + factor(Website_Campaign), data = df)</pre><pre>summary(mkmix_model$fit)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/961/1*R4EIm1O4gTPgCAsJ4HvS9Q.png" /><figcaption>Python full model output. Significant variables outlined in red. Python is giving us warnings in reference to our model. The first one, has no impact so we will ignore. For the second error, I would dig further and perhaps transform, scale or drop the variable(s) causing the collinearity error message. Image by author.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/688/1*cGyApZTKSuKpRhR4XvvB1g.png" /><figcaption>R full model output. Significant variables outlined in red. Image by author.</figcaption></figure><p>Our baseline revenue is 54,394. The only positive significant <em>(p-value is less than 0.05)</em> variable is InStore. The negative significant variables are Base_Price, Stout &amp; Website Campaign <em>(no campaign)</em>.</p><p>The generic interpretation for each of our coefficients is for every one unit increase in the x variable, the y variable <em>(NewVolSales)</em> increases by beta units.</p><p>For example, for every 1 unit increase of InStore, sales increase by 28. If our sales volume is in dollars, then this would be a 28 dollar increase.</p><h3>What can we derive from our correlation analysis and how can we use this to inform marketing?</h3><p>We will just focus on the relationship between NewVolSales and each independent (x) variable.</p><p>What’s <strong>not working</strong> in marketing?</p><ol><li>Price — <em>significant</em>. We lose money when we increase the base price.</li><li>Stout — <em>significant</em></li><li>Website Campaign —<em> significant. </em>This means when there is no website campaign going on. This has a negative effect on sales.</li></ol><p>What is <strong>working</strong> with marketing?</p><ol><li>Instore —<em> significant</em></li></ol><p>What is<strong> not as impactful</strong>?</p><ol><li>Radio —<em> not significant</em></li><li>TV —<em> not significant</em></li><li>Discount — <em>not significant</em></li></ol><p>You should at this point have a conversation with your marketing stakeholders to understand their marketing goals and tactics for each of their marketing initiatives. There may be different goals for different initiatives. For instance, if marketing is using Radio and TV for top-funnel activities, then what we see in the data makes sense. Radio and TV are great for branding (e.g. awareness), but may have less of an impact on bottom-funnel metrics like sales. So those marketing efforts that aren’t necessarily significant from a statistical point of view, can have impact from a real-world point of view.</p><h3>Summary</h3><p>With our correlation analysis we have derived some key insights into what is working and what isn’t working when it comes to increased sales. Now, it’s up to you to go further in your analysis which could include:</p><p>1. Adding in additional factors that were not included initially<br>2. Quantifying the impact of each marketing effort (e.g. ROI). In other words, calculate the marketing contribution towards sales.<br>3. Build a future forecast based on current levels of marketing spend and promotions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*PyM_xSHNVWwqlnDW" /><figcaption>Photo by <a href="https://unsplash.com/@kellysikkema?utm_source=medium&amp;utm_medium=referral">Kelly Sikkema</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>What are some of the pitfalls and drawbacks of correlation?</h3><p><strong>Pitfalls of correlation:</strong></p><p>1. Correlation does not equal causation — correlation gives us a way to<br> check if there is an association between two variables, but there<br> could be other explanations.</p><p>2. Latent or hidden variables can affect the relationship between two (2)<br> variables.</p><p><strong>Advice:</strong></p><p>1. Always check for highly correlated variables. A (correlation coefficient) r &gt; 0.9. You can do this by either checking the correlation matrix or checking the variance inflation factor (VIF).</p><p>2. If collinearity exists, remove or transform before modeling. An example transformation could be taking the natural log of a variable.</p><p>3. Model data using methods robust to collinearity, e.g. Random Forest<br> models.</p><p>The R code can be found on both <a href="https://github.com/anita-owens/Marketing-Analytics-R/blob/main/How%20to%20use%20correlation%20analysis%20to%20improve%20marketing%20performance.Rmd">Github</a> and <a href="https://rpubs.com/anitaowens/correlation-in-marketing">RPubs</a>. The Python code can be found on <a href="https://github.com/anita-owens/Marketing-Analytics-Python/blob/main/How%20to%20use%20correlation%20analysis%20to%20improve%20marketing%20performance.ipynb">Github</a>.</p><h3>References:</h3><p>[1]. Winston, W. L. (2014). Marketing analytics: Data-driven techniques with Microsoft Excel. Wiley. pp. 170–174.</p><p>[2]. Chapman, C. and McDonnell Feit, E., (2015). R for marketing research and analytics. Cham: Springer, pp.95–109, 162–191.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=156e80187d74" width="1" height="1" alt=""><hr><p><a href="https://medium.com/geekculture/how-to-use-correlation-analysis-to-improve-marketing-performance-in-python-r-156e80187d74">How to use correlation analysis to improve marketing performance in Python &amp; R</a> was originally published in <a href="https://medium.com/geekculture">Geek Culture</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to forecast with two-way ANOVA in R]]></title>
            <link>https://anitaowens.medium.com/how-to-forecast-with-two-way-anova-in-r-33d1c09790b3?source=rss-9790253b531b------2</link>
            <guid isPermaLink="false">https://medium.com/p/33d1c09790b3</guid>
            <category><![CDATA[ml-so-good]]></category>
            <category><![CDATA[forecasting]]></category>
            <category><![CDATA[regression]]></category>
            <category><![CDATA[r-programming]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Anita Owens]]></dc:creator>
            <pubDate>Thu, 31 Mar 2022 07:39:04 GMT</pubDate>
            <atom:updated>2024-03-02T08:42:55.785Z</atom:updated>
            <content:encoded><![CDATA[<p>A powerful stats technique to have in your forecasting toolbox</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*gPzU-sNQu6vZJSRR" /><figcaption>Photo by <a href="https://unsplash.com/@adoucett?utm_source=medium&amp;utm_medium=referral">Aaron Doucett</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In a previous <a href="https://medium.com/mlearning-ai/how-use-one-way-anova-for-forecasting-in-r-908bb1b5b4d3">article</a>, I walked through the steps of using ANOVA (analysis of variance) for forecasting with one-way ANOVA. In that scenario, we were forecasting book sales based on shelf location (one factor). The forecast depended upon if there was a significant relationship between the factor (shelf location) and the outcome (sales).</p><p>However, what if you have two factors? You can use two-way ANOVA for forecasting (even three-way ANOVA!), but things get little more complicated due to: 1) replication and 2) interaction.</p><h3>Replication</h3><p>If we are trying to analyze the effect of two factors (x) on one (y) variable, it needs to be observed the same number of times (referred to as k) for each combination of the two factors (x).</p><p>If <strong>k = 1</strong>, it is called two-way <strong>without</strong> replication. For instance, if we are trying to determine if two factors, such as sales territory or sales rep influences sales, we can only have <strong>one pairing</strong> of a sales rep to a sales territory. This is also called a randomized block design.</p><p>If <strong>k &gt; 1</strong>, then it’s two-way ANOVA <strong>with</strong> replication. If we want to know if advertising and price influences product sales, we <strong>can observe</strong> product sales at all levels of advertising and price.</p><blockquote><strong>ANOVA replication scenario</strong> (k = number of times)</blockquote><blockquote>K = 1<br><strong>without</strong> replication</blockquote><blockquote>K &gt; 1<br><strong>with</strong> replication</blockquote><h3>Interaction</h3><p>For our two variables of interest, we also have to be concerned with if they interact. In other words, will the <strong>combination of our two variables of interest</strong>, have any strange effects on the observation we are observing?</p><h3>ANOVA Assumptions</h3><p>Like all statistical tests, there are some assumptions that need to be made to ensure we can ANOVA. The assumptions are:</p><p>1. Data comes from random samples<br>2. The observations are independent<br>3. Normally distributed underlying data<br>4. Homogeneity of variances</p><p>However, what we <strong><em>really</em></strong> care about for ANOVA to be valid for forecasting are that the <strong>residuals</strong> or forecast errors (actual sales — predicted sales) are normally distributed and the <strong>variance</strong> of the residuals for each group is identical.</p><p>Also, let’s define our null and alternative hypotheses for two-way ANOVA:</p><blockquote>H₀ — the means of factor A are equal<br>Ha — the means of factor A are different</blockquote><blockquote>H₀ — the means of factor B are equal<br>Ha — the means of factor B are different</blockquote><blockquote>H₀ — there is no interaction between factors A&amp;B<br>Ha — there is an interaction between factors A&amp;B</blockquote><h3>Analysis: Two-way ANOVA with replication scenario</h3><p>Does advertising and coupons impact sales? We will forecast peanut butter sales (y) with advertising and coupon as our independent variables or factors (x’s). This analysis assumes that only advertising and coupons impact sales.</p><p>Let’s take a look at the dataset.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*-GYfHXGRnepUUoSDwtr-JA.png" /><figcaption>Wide dataset. Image by author.</figcaption></figure><p>We have 3 columns: 1) Advertising 2) Coupon and 3) No coupon. Our coupon columns have our sales data in units. However, we need to turn our wide dataset into a long dataset for further analysis using the pivot_longer() function.</p><pre>#Pivot data from wide to long dataset<br>(peanutbutter_long &lt;- peanutbutter %&gt;% <br>  pivot_longer(!advertising, names_to = &quot;coupon&quot;, values_to = &quot;sales&quot;))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/698/1*a6Cv-jYRZs4n9XdcgJRwFA.png" /><figcaption>Long dataset. Image by author.</figcaption></figure><p>Let’s visualize our sales data using ggline() from the ggpubr package.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/474/1*b-xAUWRwVy0PwNIb-Zu1Gw.png" /><figcaption>Peanut butter sales by advertising and coupon status. Image by author.</figcaption></figure><p>Now we complete our two-way ANOVA using the aov() function. Here, we are testing sales by main effect of advertising and coupon plus the interaction between advertising and coupon.</p><pre>two_way_aov &lt;- aov(sales ~ advertising*coupon, data = peanutbutter_long)</pre><pre>#The anova table<br>summary(two_way_aov)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/589/1*DNWQSgzcs8ctsaiItWizHw.png" /><figcaption>ANOVA summary table. Image by author.</figcaption></figure><p>Advertising is very significant (a very small p-value less than 0.001) while coupon is significant (p-value of 0.0467). The <em>advertising:coupon</em> variable does not show interaction as the p-value is very large at 0.8006. This means that advertising and coupons independently influence sales. Since there is no interaction between our two factors, then our forecast would be:</p><blockquote>Predicted sales = overall average + Factor A effect (if significant) + Factor B effect (if significant).</blockquote><p><strong>NOTE:</strong> If a factor is <strong>not significant</strong> then the factor effect is assumed to be <strong>0</strong>.</p><h4>Model Diagnostics</h4><p>The residuals can be plotted using a kernel density plot, but if you have a small dataset, it may be more useful to use a Quantile-Quantile plot (qq plot). If the data is normally distributed, the observations should fall along the diagonal line.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/775/1*JtB6uVUZ2hdysM323j_C8w.png" /><figcaption>QQ plot of the ANOVA residuals. Image by author.</figcaption></figure><p>This QQ plot makes it clear that we have a few observations along the tails are off the line which means we have a bit of skew in the data. Since most of the observations fall along the diagonal, I think we are good here and the point predictions should be good to use although the prediction intervals may be quite wide.</p><h3><strong>What can we expect in sales? (Here, I have created a table of mean sales based on each factor level)</strong></h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/09e16d14e2ee17b4565071d2b4366161/href">https://medium.com/media/09e16d14e2ee17b4565071d2b4366161/href</a></iframe><p>Ads tends to increase sales by 78 (158.33–80.67) over no ad. Coupon tends to increase sales by 21 (130–109) over no coupon.</p><h4>What can we expect in sales when there is both advertising and a coupon?</h4><p>First, calculate the overall average.</p><pre>#Calculate the overall average<br>overall_avg &lt;- mean(peanutbutter_long$sales)<br>paste(&quot;The overall sales average is&quot;, overall_avg, sep=&quot; &quot;)</pre><pre><strong>Output:</strong> <strong>The overall sales average is 119.5</strong></pre><p>Second, calculate advertising effect (with advertising subtracted by no advertising).</p><pre>#Calculate advertising effect<br>adv_effect &lt;- (158.33 - 80.67)</pre><p>Next, calculate coupon effect (with coupon subtracted by no coupon).</p><pre>#Calculate coupon effect<br>coupon_effect &lt;- (130 - 109)</pre><p>Finally, calculate the predicted value.</p><pre>#Calculate Forecast:<br>predicted_sales &lt;- overall_avg + adv_effect + coupon_effect</pre><pre>paste(&quot;Forecast when there is both advertising and a coupon is:&quot;, predicted_sales, sep = &quot; &quot;</pre><pre><strong>Output:  Forecast when there is both advertising and a coupon is: 218.16</strong></pre><h3>What if there is an interaction effect?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Sg1bo9G2A7rE30X8" /><figcaption>Photo by <a href="https://unsplash.com/@mills_digital_imaging?utm_source=medium&amp;utm_medium=referral">Adam Mills</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Here is example of a dataset that has an interaction effect. We have several weeks of video game sales (y) with advertising and price as our independent variables or factors (x’s).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/701/1*t1zSzKV8m9UnIpv6LW3tyw.png" /><figcaption>Games dataset long. Image by author.</figcaption></figure><p>Let’s visualize this dataset:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/867/1*Z7GqXoO3pyocnYAauhni6A.png" /><figcaption>Game sales by advertising and price levels. Image by author.</figcaption></figure><p>Advertising is on the x-axis, sales on the y-axis, price levels are represented via the lines.</p><p>To interpret what’s going on, let’s first take a look at the grey line. The grey line represents the high price level across all advertising levels (the x-axis) and the line is fairly parallel across all advertising levels. Both the yellow (medium price level) and blue line (low price level) show an increase in sales when we move from medium advertising to high advertising. This chart makes it clear that sales increase <strong>when ad spending increases</strong> (blue and yellow lines), but <strong>not</strong> when prices are high (the grey line).</p><p>Now we complete our two-way ANOVA using the aov() function. Here, we are testing sales by main effect of advertising and price, plus the interaction between advertising and price.</p><pre>aov(sales ~ advertising*price, data = games_long)</pre><p>The summary output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/629/1*4s9YpDB5eHGhJ-oRmcA0Aw.png" /><figcaption>ANOVA output. Image by author.</figcaption></figure><p>Since the p-value for the <strong>interaction</strong> (advertising*price) is very small (significant interaction effect), we can forecast sales for any price and advertising combination equal to the mean of the observations having that combination of factor levels.</p><h4>What can we expect in sales?</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f83862f5b6ec348153397bb72929f2e1/href">https://medium.com/media/f83862f5b6ec348153397bb72929f2e1/href</a></iframe><p>If we wanted to forecast sales when advertising is low and price is low, the forecast would be 29.67 according to our table. If advertising is high and price is low, the forecast would be 51.</p><p>All there is left to do is check the residuals for our forecasts to be valid.</p><h3><strong>Key Takeaways</strong></h3><p>The forecast equation we can use to predict with two-way ANOVA (with or without replication) is as follows:</p><blockquote>predicted value = overall average + factor A effect (if significant) + factor B effect (if significant)</blockquote><p>If a factor is <strong>not significant</strong> then the factor effect is assumed to be 0.</p><p>For two-way ANOVA (with replication), if interaction effect is <strong>significant</strong>, then the predicted value is the value of the response variable (y) is equal to the mean of all observations having that combination of factor levels. If the interaction effect, <strong>is not significant</strong>, you can proceed with your analysis as if it were a two-way ANOVA without replication scenario.<br> <br>If there is seasonality in your data, you can incorporate seasonality and proceed with two-way ANOVA for forecasting.</p><p>The code and all datasets can be found on Github and RPubs below:</p><ol><li>Forecasting with Two-Way ANOVA in R — With Replication and No Interaction <a href="https://github.com/anita-owens/Forecasting-in-R/blob/main/Forecasting%20with%20Two-way%20ANOVA%20in%20R%20-%20With%20replication%20and%20no%20interaction.Rmd">Github</a> <a href="https://rpubs.com/anitaowens/forecasting-anova-replication">RPubs</a></li><li>Forecasting with Two-Way ANOVA in R — When interaction is absent <a href="https://github.com/anita-owens/Forecasting-in-R/blob/main/Forecasting%20with%20Two-way%20ANOVA%20in%20R%20%20-%20When%20interaction%20is%20absent.Rmd">Github</a> <a href="https://rpubs.com/anitaowens/forecasting-anova-no-interaction">RPubs</a></li><li>Forecasting with Two-Way ANOVA in R — When interaction is present <a href="https://github.com/anita-owens/Forecasting-in-R/blob/main/Forecasting%20with%20Two-way%20ANOVA%20in%20R%20-%20When%20interaction%20present.Rmd">Github</a> <a href="https://rpubs.com/anitaowens/forecast-two-way-interaction">RPubs</a></li></ol><h3>References</h3><p>[1] Winston, W. L. (2014). Marketing analytics: Data-driven techniques with Microsoft Excel. 607–617. Wiley.</p><p>[2] Hyndman, R. J., Athanasopoulos, George (2021). <a href="https://otexts.com/fpp3/">Forecasting Principles and Practice.</a> 3rd ed.</p><p><a href="https://medium.com/mlearning-ai/mlearning-ai-submission-suggestions-b51e2b130bfb">Mlearning.ai Submission Suggestions</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=33d1c09790b3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How use one-way ANOVA for forecasting in R]]></title>
            <link>https://anitaowens.medium.com/how-use-one-way-anova-for-forecasting-in-r-908bb1b5b4d3?source=rss-9790253b531b------2</link>
            <guid isPermaLink="false">https://medium.com/p/908bb1b5b4d3</guid>
            <category><![CDATA[forecasting]]></category>
            <category><![CDATA[ml-so-good]]></category>
            <category><![CDATA[regression]]></category>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[r-programming]]></category>
            <dc:creator><![CDATA[Anita Owens]]></dc:creator>
            <pubDate>Wed, 26 Jan 2022 20:21:10 GMT</pubDate>
            <atom:updated>2024-03-02T08:47:39.754Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to use one-way ANOVA for forecasting in R</h3><p>The statistical test that can also forecast</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OK0bst6OtiaACMpZJWq_Eg.jpeg" /><figcaption>The English book section at my local bookstore. Image by author.</figcaption></figure><p>Imagine my surprise when I learned that Analysis of Variance (ANOVA), well regarded in hypothesis testing, can be used to forecast sales. Well it really shouldn’t be a surprise as ANOVA and regression are closely related.</p><p>ANOVA helps answer the question: <em>Are our groups really different? </em>We use ANOVA to analyze the variance of means and then we can make inferences about those means.</p><p>I will forecast product sales using one-way ANOVA. One-way as we are only using a single independent variable to forecast. If we wanted to analyze by <strong>two</strong> independent variables, that would be a two-way ANOVA. This dataset is from Chapter 40 of Wayne L. Winston’s Marketing Analytics: Data-Driven Techniques with Microsoft Excel. It contains 6 weeks of sales data for a computer book that was located on different shelf positions in the store.</p><p>This dataset has 3 columns (Front, Back, and Middle shelf location) with total sales on the rows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/782/1*Y-Axr5FLLYgfjPdEsaysNg.png" /></figure><p>ANOVA will help answer the question: <em>Does shelf location impact book sales and what can we expect in total sales?</em></p><h3>Explore Dataset</h3><p>Firstly, we need to reshape the data in order to be able to run any statistical analysis. Right now our dataset is wide and we want it to be long so that each row is simply one observation per point in time per location. We will first, add a week number as the row number and then use the pivot_longer() function from tidyr.</p><pre>books &lt;- bookstore %&gt;% <br>mutate(week_num = row_number())  %&gt;%<br>  pivot_longer(!week_num, names_to = &quot;location&quot;,<br>               values_to = &quot;sales&quot;)</pre><pre>books</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/780/1*8hbiHUCPK0yX7nnU_utfVw.png" /><figcaption>Transformed data from wide-to-long. Image by author.</figcaption></figure><p>One thing that is important to know is that there are some missing values which we will ignore in our analysis rather than removing or imputing (replacing) the missing values.</p><p>Next, let’s do some exploratory data visualization. We’ll plot sales by shelf location using a box plot to examine the distributions.</p><pre>#set Wall Street Journal theme for all plots<br>theme_set(theme_wsj())</pre><pre>ggplot(data = books, aes(x=location, y=sales)) + geom_boxplot(na.rm=TRUE) + ggtitle(&quot;Book sales by shelf location&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/846/1*euhlcTHtsVhYXJThlMFALA.png" /><figcaption>Book sales ggplot boxplot using wsj theme from ggthemes package. Image by author.</figcaption></figure><p>Average sales are higher when located at the back. We also have a few outliers represented by the black dots outside of the boxes.</p><h3>ANOVA</h3><p>Like all statistical tests, there are some assumptions that need to be made to ensure we can use our statistical test. For ANOVA, the assumptions are:</p><p>1. Data comes from random samples<br>2. The observations are independent<br>3. Normally distributed underlying data<br>4. Homogeneity of variances</p><p>Let’s define our null and alternative hypothesis:</p><p><em>H₀</em> — the means across groups are equal<br><em>Ha</em> — the means across groups are different</p><h3>ANOVA assumptions</h3><p>In order to use ANOVA, we have to ensure our underlying data meets the four (4) ANOVA assumptions outlined above. The assumptions we are most concerned with is normality and homogeneity of variances. We will check normality with the Shapiro-Wilk’s method and homogeneity of variance with the Bartlett test.</p><pre># Test normality across groups (Shapiro)<br>tapply(books$sales, books$location, FUN = shapiro.test)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/782/1*QNldDH6FSk2oCaCu87e5zw.png" /><figcaption>Shapiro-Wilk normality test output. Image by author.</figcaption></figure><p>All p-values are very large (&gt; 0.05) across all shelf positions so we can assume normality of the underlying data.</p><p>Let’s check homogeneity of variance.</p><pre># Check the homogeneity of variance (Bartlett)<br>bartlett.test(sales ~ location, data = books)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/906/1*peOFXMLPLSSP7csWxvVJGA.png" /><figcaption>Output of Bartlett test. Image by author.</figcaption></figure><p>The Bartlett test p-value is very large (&gt; 0.05), we can assume homogeneity of variance. We can now safely continue with a one-way ANOVA.</p><h3>Perform one-way ANOVA</h3><pre># Perform one-way ANOVA <br>(anova_results &lt;- oneway.test(sales ~ location, data = books, var.equal = TRUE))</pre><pre>#Extract p-value<br>anova_results$p.value &lt; 0.05 #If true, means are different. If false, mean sales are identical in all shelf positions.</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/481/1*3S2LuXpglJwQp0Il_vYpOA.png" /><figcaption>One-way ANOVA output p-value is very large so we fail to reject the null hypothesis. Image by author.</figcaption></figure><p><strong>INTERPRETATION OF ONE-WAY ANOVA RESULT:</strong><br> The p-value of the test is greater than the significance level alpha = 0.05. We can cannot conclude that sales are significantly different based on shelf height. (The p-value is higher than 5%, so we fail to reject the null hypothesis that the means across groups are equal). In other words, we accept the null hypothesis and conclude that sales are not significantly different across shelf positions.</p><h3>Forecast</h3><p>The predicted mean for each group is the overall mean. The forecast will be weekly sales irrespective of shelf location.</p><pre>#Forecast:  mean of sales and remove n/a&#39;s<br>mean(books$sales, na.rm = TRUE)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/586/1*l6ExrhyPZBCAqMBgBOsHjQ.png" /><figcaption>Forecast for weekly sales. Image by author.</figcaption></figure><p>We can expect book sales of 1,120 per week.</p><h3>Scenario 2: What if the groups have significantly different means?</h3><p>Let’s try again with a different scenario. Let’s take a look a <strong>new dataset</strong> of 6 weeks worth of sales data for our computer book. Just like our first dataset this data originally wide and we transform it to a long format.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m89esw1uyh3WJKMUVGI08Q.png" /><figcaption>Transformed data from wide-to-long. Image by author.</figcaption></figure><p>Let’s plot this dataset on a box plot.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/708/1*1RM_Dc_aN0VFzjAls8hiQw.png" /><figcaption>Book sales for scenario 2 with ggplot boxplot using wsj theme from ggthemes package. Image by author.</figcaption></figure><p>Within this dataset, we see significantly more sales for books located at the back when comparing to the front and middle locations.</p><h3>ANOVA Assumptions (Scenario 2)</h3><pre># Test normality across groups<br>tapply(books2$sales, books2$location, FUN = shapiro.test)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/544/1*fHxig7OEiC8yjMuS9566rg.png" /><figcaption>Shapiro-Wilk test output. Image by author.</figcaption></figure><pre># Check the homogeneity of variance<br>bartlett.test(sales ~ location, data = books2)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/449/1*jgVyCwe-t4OOLhK1iRcFnA.png" /><figcaption>Bartlett test output. Image by author.</figcaption></figure><p>Bartlett test p-value is also very large.</p><h3>Perform One-way ANOVA again</h3><pre># Perform one-way ANOVA <br>(anova_results2 &lt;- oneway.test(sales ~ location, data = books2, var.equal = TRUE))</pre><pre>anova_results2$p.value &lt; 0.05 #If true, means are different. reject null hypothesis and alternative hypothesis is true. if false, mean sales are identical in all shelf positions.</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/495/1*heA7uIkX2oFJ6wP-vcakRQ.png" /><figcaption>ANOVA output for scenario 2. Image by author.</figcaption></figure><p>INTERPRETATION OF ONE-WAY ANOVA RESULT:<br>The p-value is very small 0.003426 so we reject the null hypothesis and conclude that sales are significantly different across shelf positions.</p><h3>Forecast (when we have significantly different means)</h3><p>The predicted mean for each group equals the group mean.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/603/1*mW787dlxnWBZyyDqChT-eA.png" /><figcaption>Forecast of weekly sales based on result of ANOVA. Image by author.</figcaption></figure><p>We can expect sales of 900 books to be sold per week when located at the front, 1100 per week when located at the middle, and 1400 when located at the back of the book section.</p><h3>Key Takeaways</h3><p>When using one-way ANOVA for forecasting:</p><blockquote>Forecast if mean of sales are <strong>not significant</strong> across groups:<br> The predicted mean for each group equals the <strong>overall mean</strong>.</blockquote><blockquote>Forecast if mean of sales <strong>are</strong> <strong>significant </strong>across groups:<br> The predicted mean for each group equals the <strong>group mean</strong>.</blockquote><p>Code can be found on <a href="https://github.com/anita-owens/Forecasting-in-R/blob/main/Forecasting%20with%20One-way%20ANOVA%20in%20R.Rmd">Github</a> and <a href="https://rpubs.com/anitaowens/forecasting-anova">Rpubs</a>.</p><h3>References:</h3><p>Winston, W. L. (2014). Marketing analytics: Data-driven techniques with Microsoft Excel. Wiley.</p><p><a href="https://medium.com/mlearning-ai/mlearning-ai-submission-suggestions-b51e2b130bfb">Mlearning.ai Submission Suggestions</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=908bb1b5b4d3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to code in Python within R Studio]]></title>
            <link>https://blog.devgenius.io/how-to-code-in-python-within-r-studio-caaec54c9d74?source=rss-9790253b531b------2</link>
            <guid isPermaLink="false">https://medium.com/p/caaec54c9d74</guid>
            <category><![CDATA[r]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Anita Owens]]></dc:creator>
            <pubDate>Mon, 27 Dec 2021 09:19:38 GMT</pubDate>
            <atom:updated>2024-03-02T08:49:24.375Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Get up and running with Anaconda and reticulate in R Markdown</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iyIiUURxyrhtJcE5WYXVWg.jpeg" /><figcaption>Even my kid’s stuffed toy prefers RStudio. Image by author.</figcaption></figure><p>I never really understood the Python vs. R debate or why there are countless articles about it. I’m a strong believer you should use whatever tool you are most comfortable with that gets the job done.</p><p>When I work in Python, I use either a Jupyter notebook or Spyder as my IDE <em>(Integrated Development Environment)</em> of choice. They are good IDE’s and there are many more for working with Python, but I really prefer the bells and whistles of RStudio for data analysis. You can have the benefits of working in RStudio with Python by using the <a href="https://rstudio.github.io/reticulate/">reticulate</a> package which acts as a Python interface.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*fPxTRZjZQ-1Fql1YDSt98A.png" /><figcaption>Source: <a href="https://rstudio.github.io/reticulate/">https://rstudio.github.io/reticulate/</a>. Image by author.</figcaption></figure><h3>How to get started</h3><p>First, make sure to install <a href="https://docs.anaconda.com/anaconda/install/index.html">Anaconda</a> or Miniconda. Anaconda is a Python distribution platform that makes working in Python much easier. Once installed, verify your installation by opening the Anaconda Navigator application. If it opens, you were successful.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-AAU2K5s4_tRv3ueaPKvJA.png" /><figcaption>Source: <a href="https://docs.anaconda.com/anaconda/install/index.html">https://docs.anaconda.com/anaconda/install/index.html</a>. Image by author.</figcaption></figure><p>Back in RStudio, open up a new R Markdown document. Insert an R chunk to install and load the reticulate package. For reference, I am using a MacBook running macOS Monterey Version 12.0.1</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/716/1*vnVQ-7z5rrHWS7KG-SEkhw.png" /><figcaption>Install and load R libraries. Image by author.</figcaption></figure><p>Next, check your Python environments using the <a href="https://rstudio.github.io/reticulate/reference/conda-tools.html">conda_list()</a> function. The dataframe output in the first column shows that I have two (2) Python environments: r-reticulate and anaconda3. The second column returns the path of the Python environment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/584/1*Uf4ESINMTQEbiZ11aQv9Cw.png" /><figcaption>Python environment check. Image by author.</figcaption></figure><p>The use_condaenv() function lets you declare which environment to use. I will declare the anaconda3 environment as I find it easier to work with.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/610/1*xtZV2u75x9UnBOgEo9GpiQ.png" /><figcaption>Declare Python environment. Image by author.</figcaption></figure><p>Next, install Python packages using py_install() function. I will concatenate the Python packages I require for my analysis. The output window will show you the status of your downloaded packages and what if any updates occurred.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/714/1*vM3dY9zsqLweT5ZjheJybw.png" /><figcaption>Install Python packages with py_install(). Image by author.</figcaption></figure><p><strong><em>NOTE:</em></strong><em> If you have trouble with installing packages using py_install() due to errors, install packages via the command line (your operating system’s terminal window) using </em><a href="https://packaging.python.org/en/latest/tutorials/installing-packages/"><em>pip install</em></a><em> before running py_install() in R.</em></p><p>Next, instead of inserting an R chunk, we can insert a Python chunk.</p><figure><img alt="Insert Python chunk gif" src="https://cdn-images-1.medium.com/max/909/1*iTxfR15uKfWmBAijweEMYQ.gif" /><figcaption>Insert Python chunk. Image by author.</figcaption></figure><p>Now that I have inserted a Python chunk, I will go ahead and import my Python libraries.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/613/1*rJdDqQzHM-OKnKvn66eRhw.png" /><figcaption>Import Python packages. Image by author.</figcaption></figure><p>Now you can use your Python libraries and proceed as if you were in a Python editor.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/608/1*-xWFVCHbu00XAsT86jhbTw.png" /><figcaption>Import csv file using pandas read_csv function and print to console. The Credit dataset comes from the book, An Introduction to Statistical Learning. Source: <a href="https://www.statlearning.com/">statlearning.com</a>. Image by author.</figcaption></figure><p>Check out the Python environment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_kZlAuwEKNQmxs5ERADC5g.gif" /><figcaption>You can alternate between Python and R environments. Image by author.</figcaption></figure><p>The Python console.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xST6gNao14fxhvPFsR-xtA.gif" /><figcaption>Image by author</figcaption></figure><p>Python environment in RStudio.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iy6cMSjKuU8KOd_oDpbAcw.png" /><figcaption>Python Environment in RStudio. Image by author.</figcaption></figure><p>There are different ways to use Python in RStudio’s IDE, including sourcing Python scripts, that can be found in the <a href="https://rstudio.github.io/reticulate/articles/rstudio_ide.html">reticulate</a> documentation. The package authors suggest using a Python editor for Python-only projects. Nevertheless, reticulate allows you the flexibility of having both R and Python together without leaving RStudio.</p><p>Full code can be found on <a href="https://github.com/anita-owens/Python-in-R/blob/main/How%20to%20code%20in%20Python%20within%20R%C2%A0Studio.Rmd">Github</a>.</p><h3>References</h3><p><a href="https://rstudio.github.io/reticulate/">Interface to Python</a></p><p>James, G. (2021). An Introduction to Statistical Learning: With Applications in R. Springer. <a href="https://www.statlearning.com/">https://www.statlearning.com/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=caaec54c9d74" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/how-to-code-in-python-within-r-studio-caaec54c9d74">How to code in Python within R Studio</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to forecast product sales in the R Tidyverse with Modeltime and Prophet]]></title>
            <link>https://anitaowens.medium.com/how-to-forecast-product-sales-in-the-r-tidyverse-with-modeltime-and-prophet-cd509506940d?source=rss-9790253b531b------2</link>
            <guid isPermaLink="false">https://medium.com/p/cd509506940d</guid>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[r]]></category>
            <category><![CDATA[tidyverse]]></category>
            <category><![CDATA[forecasting]]></category>
            <dc:creator><![CDATA[Anita Owens]]></dc:creator>
            <pubDate>Mon, 22 Nov 2021 13:02:38 GMT</pubDate>
            <atom:updated>2024-03-02T08:51:47.827Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aBTOUoFEOIBnqEeJK4R1xQ.png" /><figcaption>Tidyverse ecosystem + Facebook’s Prophet. Image by author.</figcaption></figure><p>Tidyverse has changed the game when it comes to data analysis in R. The Tidyverse ecosystem also includes tidy machine learning that makes exploring, analyzing and manipulating complex machine learning objects easy thanks in part to the List Column Workflow. I wanted to give forecasting in the Tidyverse a try using the <a href="https://business-science.github.io/modeltime/">modeltime package</a>, developed by Matt Dancho, which was built for tidy time series forecasting which follows a streamlined workflow.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/893/1*30QXVoT_MGYRM8317bGc7g.png" /><figcaption>Modeltime Workflow: <a href="https://business-science.github.io/modeltime/">https://business-science.github.io/modeltime/</a> Image by author.</figcaption></figure><p>The Tidyverse machine learning workflow taps into many different machine learning models including the <a href="https://facebook.github.io/prophet/">Prophet</a> package created by Facebook’s Core Data Science team. Prophet is robust to trends in time series data including daily, weekly and yearly seasonality. Trend in time series data is a specific pattern which in which observations are either increasing or decreasing over time. Also, trends can constantly change. The <a href="https://facebook.github.io/prophet/">Prophet</a> package was designed to be robust to changing trends, missing data, and outliers so we will use this package to model and forecast our sales data.</p><p>This dataset is from Chapter 31 of Wayne L. Winston’s <a href="https://www.amazon.com/Marketing-Analytics-Data-Driven-Techniques-Microsoft/dp/111837343X">Marketing Analytics: Data-Driven Techniques with Microsoft Excel</a>. We have three (3) years of daily sales of Post-its. Those lovable note snippets that hang around your desk.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q8cHlwYODDoEnI2wieUN7A.png" /><figcaption>According to 3M, Post-its have been around 40+ years, but took a while for consumers to catch on. Source: <a href="https://www.post-it.com/3M/en_US/post-it/contact-us/about-us/">https://www.post-it.com/3M/en_US/post-it/contact-us/about-us/</a></figcaption></figure><p><strong>We will do the following:</strong></p><ol><li>Determine which factors influence sales</li><li>Build a model to forecast daily sales</li></ol><h3><strong>Explore dataset</strong></h3><p>Let’s import and check our data. We have 6 variables:</p><ol><li>Month (The month as a number)</li><li>Day number</li><li>Day (This is our date variable but since we imported from Excel we get the Excel formatted dates)</li><li>Pricing for that particular day (7 different prices)</li><li>Display (this is a binary variable. 1 indicates that our product was on a display for that day. 0 indicates that it was not on display).</li><li>Actual sales</li></ol><p>We have to do a bit of transformation to get our data in the right format. First, let’s create a new formatted date column as our data column inherited the Excel date formatting.</p><pre>#Create New Formatted Date Column supplying origin argument<br>postit$new_date &lt;- as.Date(postit$Day, origin = &quot;1899-12-30&quot;)</pre><pre>#Check results<br>str(postit$new_date)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/628/1*ByUowJFq2GGrhaVsc9kiaw.png" /><figcaption>Reformatted date column</figcaption></figure><p>Let’s factor some variables.</p><pre>#Create list of variables that need transformation<br>fac_vars &lt;- c(&quot;Month&quot;, &quot;display&quot;)</pre><pre>#Factor Month, Display and Price Variables<br>postit[,fac_vars] &lt;- lapply(postit[,fac_vars], factor)</pre><pre>#Check results<br>str(postit)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/532/1*bN-qVea587jKSIQ_Cp2sZQ.png" /><figcaption>Results of factoring</figcaption></figure><p>Let’s visualize our sales over time with plot_time_series() function from the timetk package. If you set .interactive = TRUE argument, then your plot is an interactive Plotly plot.</p><pre>#From timetk package - visualize sales<br>postit %&gt;%<br>  plot_time_series(new_date, actualsales, .interactive = TRUE)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/643/1*85qiV1BDHHAMmtjDvWqkRw.png" /><figcaption>Time series plot of sales. Image by author.</figcaption></figure><p>Our plot of sales indicates that there is a positive trend of sales for our Post-its.</p><h3><strong>Task 1: What factors influence sales</strong></h3><p>First, let’s create some data visualizations of actual sales.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fjn7FmMLL7ouKBGFo5wIHg.png" /><figcaption>Plots: Histogram of sales, histogram of log(sales), boxplot of sales by month, and boxplot of sales by price. Image by author.</figcaption></figure><p>Sales are a bit skewed to the right, but looks normal after log transformation. Sales are lowest in March. Sales are generally higher in Q4 and the highest in December. December also appears to have the largest spread of sales. Some outliers during months August and September. Plotting sales by price reveals quite interesting insights. Sales are <strong>highest</strong> when the price is 5.95. Sales decrease when price increases to 6.1 and so and so forth where the lowest sales happen when the price is at its highest 7.52. There appears to be a relationship between price and sales.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-ntzsXWjTL88FzHDblhOlQ.png" /><figcaption>Plot of sales by display and summary stats output of sales (mean, median and standard deviation).</figcaption></figure><p>More sales when there is a display. Average sales are 639 vs 587.</p><p>Now we have some idea of the factors that appear to influence sales, we can quantify the relationships with a linear regression model.</p><p>The first step of building a linear regression model is to build the model specification. We will build the model to fit actual sales as explained by only Month, Price and Display.</p><pre># Model Spec<br>model_spec_lm &lt;- linear_reg() %&gt;%<br>set_engine(“lm”)</pre><pre># Build Linear Regression Model<br>model_fit_ln &lt;- model_spec_lm %&gt;%<br>fit(actualsales ~ Month + Price + display, data = postit)</pre><pre>#Print summary of model in a tidy object<br>lm_summary &lt;- tidy(model_fit_lm) %&gt;% <br>              mutate(significant = p.value &lt;= 0.05)<br>lm_summary</pre><pre>#If you prefer the classic R-style model output, you can use summary function to print fit to console<br>summary(model_fit_lm$fit)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/453/1*7uwBomwdPB0UlRfW61Swsg.png" /><figcaption>Tidy output of linear regression model. Image by author.</figcaption></figure><p>A generic interpretation of our linear regression model. For every one unit increase in coefficient (term column), increases (if positive) or decreases (if negative) sales by the value of our estimate, while all other variables remain at the same level.</p><p>Most months are significant but December is positive and the most statistically significant. Time of year does appear to have an impact sales.</p><p>All price coefficients are negative and significant which means that all price levels (not on our intercept) reduces sales.</p><p>For display advertising, we can expect an increase of approximately 63 when our product is on display.</p><p><strong>Evaluate linear regression model fit</strong></p><pre>#Use the glance function from the broom package to get additional information from the model (e.g. model statistics like r-squared)<br>glance(model_fit_lm)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/741/1*_bN1JSY3DHrRhdeGAZD5jw.png" /><figcaption>Model statistics in a data frame. Image by author.</figcaption></figure><p>Assessing model fit gives us information that the model we built is reasonable enough for us to derive insights. As for the model statistics, we have a very low p-value and an r-squared of .795, which tells us that that 80% of the variation in sales is explained by our independent/explanatory variables.</p><p>We built this linear model for explanatory purposes and gaining insights into what factors drives sales. Now on to model building for the forecasting task.</p><h3><strong>Task 2: Build a forecast model for sales</strong></h3><p><strong>Step 1: Split dataset into test and training data</strong></p><p>We will split our dataset into test and training data. We will use the last 12 months of the dataset as the training set.</p><pre>#Step 1: Split data into test and training set<br>splits &lt;- postit %&gt;%<br>  time_series_split(date_var = new_date, assess = &quot;12 months&quot;, cumulative = TRUE)</pre><pre>#Visualize test train split<br>splits %&gt;%<br>  tk_time_series_cv_plan() %&gt;%<br>  plot_time_series_cv_plan(new_date, actualsales, .interactive = TRUE)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/641/1*USOYabufmUrw3IfCqzIk1A.png" /><figcaption>Time Series Cross Validation Plot</figcaption></figure><p><strong>Step 2: We want to define our model specification and fit the model. We will be using prophet.</strong></p><pre># Step 2: Model Specification and Model fit<br>model_spec_prophet &lt;- prophet_reg() %&gt;%<br>    set_engine(&quot;prophet&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/401/1*U-yqLUXrXnVIUJ2GFz8pFw.png" /><figcaption>Prophet model output</figcaption></figure><p><strong>Step 3: Put model into modeltime table</strong></p><pre>#Step 3: Put model into a modeltime table<br>models_tbl &lt;- modeltime_table(model_fit_prophet)</pre><pre>models_tbl</pre><p><strong>Step 4: Calibrate model</strong></p><p>Calibration step computes the forecast predictions and residuals from the test set.</p><pre>#Step 4: Calibrate model<br>calibration_tbl &lt;- models_tbl %&gt;% <br>  modeltime_calibrate(new_data = testing(splits))</pre><pre>#Can also print calibration model to console<br>calibration_tbl</pre><p><strong>Step 5: Get accuracy metrics</strong></p><pre>#Step 5: Get Accuracy Metrics<br>calibration_tbl %&gt;%<br>    modeltime_accuracy()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/613/1*-IvlgBmG5SKMs6k5oqAMCw.png" /><figcaption>Accuracy measures in a tidy data frame. Image by author.</figcaption></figure><p>When determining error and accuracy, there are several different measures to evaluate forecasts, but I will focus on the following two (2):</p><p><strong>Mean Absolute Error (MAE):</strong> how far away our predictions from the actual value in absolute terms and is on the same scale as the data.</p><p><strong>Mean Absolute Percentage Error (MAPE):</strong> how far away our predictions from the actual value in absolute percentage terms so the prediction values are not dependent on scale.</p><p>I pay attention to the MAPE as it is often used in business to measure forecasts. Percentage error = (actual — forecast) / actual.</p><p>The MAE tells us how off we are by unit sales and the MAPE tells us we are off our forecasts are by percentage amount. This helps to put our forecasts in better context for business stakeholders.</p><pre>#Plot the residuals<br># Out-of-Sample data (test set)<br>#Change new_data argument if you want to plot in-sample residuals (training set). Timeplot is the default but can change to acf or seasonality plot.<br>calibration_tbl %&gt;%<br>    modeltime_calibrate(new_data = testing(splits)) %&gt;%<br>    modeltime_residuals() %&gt;%<br>    plot_modeltime_residuals(.interactive = TRUE, .type = &quot;timeplot&quot;)</pre><p>We want our time series residuals to hover around zero. Everything seems okay until November and December as we start to see more variability in the residuals.</p><p><strong>Step 6: Create future forecast on test set</strong></p><pre>#Step 6: Create future forecast on test data<br>(forecast_tbl &lt;- calibration_tbl %&gt;%<br>    modeltime_forecast(<br>        new_data    = testing(splits),<br>        actual_data = postit,<br>        keep_data = TRUE #Includes the new data (and actual data) as extra columns with the results of the model forecasts<br>    ))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/822/1*mOUeGqGgPyjktJOWSBAa4w.png" /><figcaption>future forecast data frame. Image by author.</figcaption></figure><p>When you open the tibble (data frame) for the forecast model, the .key column indicates whether the .value column is the actual value or the prediction value. This model’s predictions starts on row 1097.</p><p><strong>Step 7: Plot modeltime forecast on the test data</strong></p><pre>#Step 7: Plot modeltime forecast - this is the test data<br>plot_modeltime_forecast(forecast_tbl)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/802/1*A-sCSChgfbM1KGwsa3shsQ.png" /><figcaption>Modeltime forecast plot. Image by author.</figcaption></figure><h3><strong>Forecast sales into the future</strong></h3><p>If you have a time series data that is univariate, you can simply use the modeltime_forecast() function and specify the horizon (h) argument to get a forecast into the future, but since our postit data has xregs (independent regressors), we must create a new dataf rame with the xregs needed to fit the future values.</p><p>Here, I created a new data frame to hold our future forecasts. The code to create this new data frame is pretty lengthy so I will omit it here, but can be found on <a href="https://github.com/anita-owens/Forecasting-in-R/blob/main/Forecasting%20Sales%20in%20the%20Tidyverse%20with%20Modeltime%20and%20Prophet%20in%20R.Rmd">Github</a>. Notice the date starts on the first of January 2014.</p><pre>#Check results<br>str(explanatory_data)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/529/1*4GZiQNTiRIIhbfT5zvzE3A.png" /><figcaption>Structure of new data frame</figcaption></figure><p><em>CAUTION: It is super important that the data in your new data frame matches the exact same formatting, same column names, and be of the same object types of the of the data used in building the forecast. If errors occur during either the model fit or forecasting phase, differently formatted data or column names could be a possible culprit.</em></p><p><strong>Create future forecast.</strong></p><pre>#First, refit to the full dataset<br>refit_tbl &lt;- calibration_tbl %&gt;%<br>  modeltime_refit(data = postit)</pre><pre>#Specify the H or horizon argument to get a forecast into the future, but if using xregs (independent regressors), you must create a new tibble/data frame with the xregs to be used.</pre><pre>#Forecast on the new tibble data frame<br>forecast_tbl_future_data &lt;- refit_tbl %&gt;%<br>    modeltime_forecast(<br>        new_data    = explanatory_data<br>    )</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/524/1*7DdC3WENZvwyaVIL07PVuw.png" /><figcaption>Tibble of future forecasts. Image by author.</figcaption></figure><p>Tibble of the forecasts gives us the predicted values with the confidence intervals.</p><pre>#plot forecast<br>plot_modeltime_forecast(forecast_tbl_future_data, .interactive = TRUE)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/855/1*vyw9CKptUT2Wqqu4TuOZxA.png" /><figcaption>Forecast plot. Image by author.</figcaption></figure><h3><strong>How do we know if our forecasts are any good?</strong></h3><p>As the forecaster, it’s your job to reduce error, but most importantly you need a benchmark to determine how much error is acceptable and gradually reduce the error of your forecasts over time.</p><p>One easy way is to use several different methods and average your forecasts. I have found that by adding more historical data to the testing phase reduced my forecast error by a percentage reduction of 15%. I am now starting to add value to the business.</p><h3><strong>Final Summary</strong></h3><p><strong>1: What factors influence sales</strong></p><p>Price (More sales at the lowest price point. Higher prices reduces sales.)</p><p>Display (More sales when product is on display)</p><p>Month of year (December the highest. March the lowest).</p><p><strong>2: Build a forecast model for sales</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KhhIIx8S6nliYx87O4fYDg.png" /><figcaption>Our forecasts in a nice table and bar chart</figcaption></figure><p>Alternatively, for business stakeholders, you could plot your forecasts against actual sales for comparison in a dual line chart.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/889/1*sDfoBjOtDZsa6sx7YUEbBg.png" /><figcaption>Forecasts plotted against actual sales. Image by author.</figcaption></figure><p>Alternatively, you could also create forecasts of different scenarios and plot against actual sales data especially if you need to build a business case to implement your recommendations.</p><p>Full code can be found on <a href="https://github.com/anita-owens/Forecasting-in-R/blob/main/Forecasting%20Sales%20in%20the%20Tidyverse%20with%20Modeltime%20and%20Prophet%20in%20R.Rmd">Github</a> and <a href="https://rpubs.com/anitaowens/forecasting-r-modeltime">Rpubs</a>.</p><h3>Final Thoughts</h3><p>I really enjoyed performing time series analysis using Modeltime package. As a Tidyverse user, this way of working with machine learning models is streamlined, functional and flexible plus the added benefit of being able to compare many models at once.</p><h3><strong>References:</strong></h3><p>[1] Winston, W. L. (2014). Marketing analytics: Data-driven techniques with Microsoft Excel. Wiley.</p><p>[2] Forecasting: Principles and Practice (3rd ed) Rob J Hyndman and George Athanasopoulos, Monash University, Australia. <a href="https://otexts.com/fpp3/">https://otexts.com/fpp3/</a></p><p>[3] <a href="https://business-science.github.io/modeltime/">https://business-science.github.io/modeltime/</a></p><p>[4] <a href="https://facebook.github.io/prophet/">https://facebook.github.io/prophet/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cd509506940d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to forecast sales with advertising spend in R]]></title>
            <link>https://medium.com/geekculture/how-to-forecast-sales-with-advertising-spend-in-r-36e6fc99760a?source=rss-9790253b531b------2</link>
            <guid isPermaLink="false">https://medium.com/p/36e6fc99760a</guid>
            <category><![CDATA[forecasting]]></category>
            <category><![CDATA[regression]]></category>
            <category><![CDATA[analytics]]></category>
            <category><![CDATA[r]]></category>
            <category><![CDATA[marketing-analytics]]></category>
            <dc:creator><![CDATA[Anita Owens]]></dc:creator>
            <pubDate>Thu, 21 Oct 2021 02:16:13 GMT</pubDate>
            <atom:updated>2024-03-02T08:53:37.353Z</atom:updated>
            <content:encoded><![CDATA[<p><em>How do you incorporate different monthly levels of advertising in your sales forecast?</em></p><figure><img alt="Three (3) one dollar American bills" src="https://cdn-images-1.medium.com/max/1024/1*TfzUJXd2aBS9qkN2kZD7vQ.png" /><figcaption>It takes money to make money! Or does it?</figcaption></figure><p>Sales forecasting based on historical data is an important and critical process for any business. Regression is great for forecast building as you can predict a numeric output based on independent factors like time. However, what if you wanted to add additional independent variables like advertising spend in your forecast? In comes <strong>dynamic regression modeling.</strong></p><p>Dynamic regression models takes other factors into consideration besides the history of the data. The difference between linear regression and dynamic regression is the error term is an <strong>Auto-Regressive Integrated Moving Average (ARIMA)</strong> process. ARIMA models are a forecasting technique that usually provides accurate forecasts with data that involves multiple independent variables (advertising) that influence our dependent variable (sales).</p><p>I will forecast sales taking into account advertising using dynamic regression. This dataset is from Chapter 34 of Wayne L. Winston’s Marketing Analytics: Data-Driven Techniques with Microsoft Excel. It contains 36 months of sales data for a diet product.</p><p>Our dataset has 3 variables:</p><ol><li>Month</li><li>Sales (in thousands USD)</li><li>Advertising Spend (in thousands USD)</li></ol><p>But before we dig in, we need to understand a few concepts around the behavior of time series data. Time series data can contain specific patterns which include:</p><p><strong>Trend </strong>— observations are either increasing or decreasing over time.<br><strong>Seasonality </strong>— observations show cycles due to the calendar (e.g. quarterly, monthly, annually etc).<br><strong>Cyclic</strong> — observations rises and falls, but not due to a fixed period.<br><strong>Stationary or fixed</strong> — observations do not show any trend or seasonality. In other words, there are no predictable patterns.</p><p>Other important time series concepts to know are:</p><p><strong>White noise </strong>— time series data that is purely random.</p><p><strong>Ljung-Box test </strong>— a significance test to determine if data are white noise. A small p-value indicates the data are probably not white noise.</p><h3>Explore dataset</h3><p>Let’s get a sense of the data so we will run the describe() function from the psych package. This step provides a good summary of our dataset.</p><pre>#Use describe function from psych package. It gives a good overview of the dataset variables including summary statistics.</pre><pre>describe(diet)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/874/1*KJQ2j3j3fYHFrfWgvA6X7g.png" /><figcaption>describe() function output</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/721/1*HnzHxzjBEm3lQeQxiZNcvQ.png" /><figcaption>Scatterplot of Advertising and Sales</figcaption></figure><p>First, a scatterplot of sales and advertising. Sales are generally high when advertising spend is high which is perhaps not a big surprise, but this is not necessarily always the case. There seems to be wide variability between sales and advertising and the points all over the place and very far away from our linear line.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O0ssBVqrCtKl4-WEJ_Lh8A.png" /><figcaption>Line chart of sales</figcaption></figure><p>If we look at our sales data over time, we can see a lot of peaks and dips. There are definitely many dips, some seemingly random and a few around months 12, 24 and now 36 which suggests that sales are down around the Christmas holidays, but picks back up rather quickly. This might be typical behavior of the sales of a diet product, but since we don’t have the actual time index for this dataset, we will not assume that this is the case. There are also other dips during other months, but no obvious patterns that stick out.</p><h3>About ARIMA Models</h3><p>ARIMA models considered an advanced forecast model because other time series models cannot handle multi-variate forecasts. In addition, ARIMA models can detect trend, seasonality, &amp; recency. ARIMA has three (3) parameters or notations: (p, d, q).</p><p>p = autoregressive<br>d = differencing (seasonality)<br>q = moving average</p><p>Autoregressive models forecasts our variable of interest (in this case sales) using a linear combination of the past values of our variable. Differencing is simply the differences between consecutive observations. Moving average models forecasts future values using past forecast errors in a regression-like model.</p><h3>How to create an ARIMA object in R</h3><p>In order to create an ARIMA model, our data needs to be a time series object so we use the ts() function to transform our data frame. We don’t need to include Column 1 as this is our month variable (as an integer sequence and not a time index, but this is okay), so we will just subset columns 2 and 3.</p><pre>#Convert dataframe to time series object using the ts() function<br>diet_ts &lt;- ts(data = diet[,c(2,3)])</pre><pre>#Check results of transformation<br>diet_ts</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/218/1*QT29cJxjYICnnUT5sS4RgQ.png" /><figcaption>The first 16 rows of our time series object</figcaption></figure><p>Next, let’s create a time plot of both variables.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f3sH6hRk7EjQboQIxNFMAw.png" /><figcaption>Time plot of sales and advertising</figcaption></figure><p>Seeing both line charts next to one another can reveal quite a bit of insights. Both line charts appear to have the same shape (dips and peaks in the same places), but this is not always true. At month 30, advertising spend is very low, but sales were still relatively high at this month. One reason why is that past advertising can affect present and future sales. Exposure to an ad from 6 months or even 1 month ago, could generate a sale today. Factors that might have a diminishing effect over time, like advertising can be used in a regression model, but we will leave that for another day.</p><h3>Dynamic Regression Modeling</h3><p>Now we will fit our ARIMA model using the auto.arima() function from the forecast package. The auto.arima function() will decide the best model. The formula used in our function is “Sales” as explained by our xreg of “Advertising”. For the purpose of this exercise, we will also add the argument stationary = TRUE. Stationary means that the time series is stable over time or has no trend.</p><pre># Fit ARIMA model<br>fit &lt;- auto.arima(diet_ts[, &quot;Sales&quot;], xreg = diet_ts[, &quot;Advertising&quot;], stationary = TRUE)</pre><pre># Check model fit<br>fit</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/492/1*LDA67MRTbHwJzMzCLV6m9A.png" /><figcaption>ARIMA model output</figcaption></figure><h3>Output Interpretation</h3><p>The auto.arima() function has fit a linear regression model to the advertising variable and an ARIMA (1,0,0) model for the errors (1 autoregressive parameter with 0 differences and 0 moving average parameter). Our coefficient for advertising is in the first in the xreg column. So, the interpretation is, for every $1,000 increase in advertising expenditure, the unit sales increase by 0.09. The coefficient is pretty small, but it is positive.</p><h3>Residuals</h3><p>We will use the checkresiduals() function to get the residuals. The function does two (2) important things:</p><ol><li>Performs a Ljung-Box test.</li><li>Provides a time plot of the errors, an autocorrelation (ACF) plot, and a histogram of the residuals.</li></ol><pre>#Check Residuals<br>checkresiduals(fit)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/426/1*Baqvsy1xC711MU55duonhA.png" /><figcaption>Ljung-Box test output</figcaption></figure><p>P-value is larger than 0.05 so the residuals are white noise.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/690/1*_JZhp65q04W3YwMHmr4ngQ.png" /><figcaption>checkresiduals() plot of errors, ACF, &amp; residuals</figcaption></figure><p>The residuals look nearly normally distributed.</p><h3>Forecasting Sales</h3><p>Now that we have a model, we can use it to create our forecast.</p><pre>#We need to provide forecast with the future value of our predictor which is Advertising. So here, we will spend 5 in month 1, 12 in month 2 and 40 in month 3.</pre><pre>#Create a vector to hold advertising spend<br>adv_spend &lt;- c(5, 12, 40)</pre><pre>#Let&#39;s build the forecast<br>diet_fc &lt;- forecast(fit, xreg = adv_spend)</pre><pre># Plot forecast<br>autoplot(diet_fc) + xlab(&quot;Month&quot;) + ylab(&quot;Sales&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/673/1*-xKXYPd4PfI_3N-y9u_QMA.png" /><figcaption>Plot of sales data with three (3) month forward forecast</figcaption></figure><p>Our forecast plot looks reasonable given our inputs. We can also print out our forecasts (the Point Forecast column) with confidence intervals by calling our forecast object directly in the console.</p><pre>#Print forecast with confidence intervals<br>diet_fc</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/529/1*JaBlzfY1dCVO2s9nPZ8sxg.png" /></figure><p>But let’s put our forecasts into a pretty table instead. We now have projected our sales for the next quarter.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/487/1*5FcVHrLiJrlT3PbMmiR5Fg.png" /><figcaption>Table with our forecasts using ggpubr package</figcaption></figure><h3>Recap:</h3><ol><li>We built a dynamic regression model using advertising as our independent variables and sales as our dependent variable. We interpreted our advertising coefficient and it’s impact on sales.</li><li>We forecasted sales for the next quarter with different levels of advertising spend for each month.</li><li><strong>Business use case: </strong>We can use this technique to provide short-term forecasts to marketing. Perhaps your marketing manager wants to know what sales could be expected based on different ad spend scenarios in order to plan marketing activities or reach sales targets.</li></ol><p>Full code can be found on <a href="https://github.com/anita-owens/Forecasting-in-R/blob/main/How%20to%20Forecast%20Sales%20with%20Advertising%20Spend%20in%20R.Rmd">GitHub</a>. <a href="https://github.com/anita-owens/Forecasting-in-R/blob/main/How%20to%20Forecast%20Sales%20with%20Advertising%20Spend%20in%20R.Rmd">GitHub</a> version includes a training dataset to build our forecast model and testing the model on out-of-sample data.</p><h3>References:</h3><p><a href="https://www.wiley.com/en-ax/Marketing+Analytics:+Data+Driven+Techniques+with+Microsoft+Excel-p-9781118373439">Winston, W. L. (2014). Marketing analytics: Data-driven techniques with Microsoft Excel. Wiley.</a></p><p><a href="https://otexts.com/fpp2/">Forecasting: Principles and Practice (2nd ed) Rob J Hyndman and George Athanasopoulos, Monash University, Australia.</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=36e6fc99760a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/geekculture/how-to-forecast-sales-with-advertising-spend-in-r-36e6fc99760a">How to forecast sales with advertising spend in R</a> was originally published in <a href="https://medium.com/geekculture">Geek Culture</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>