<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
<channel>
<atom:link href="http://www.quantitative-consulting.eu/RSS_RBlog_QC.xml" rel="self" type="application/rss+xml" />
<title>Quantitative Consulting - R analytics blog</title>
<link>http://www.quantitative-consulting.eu</link>
<description>
The R analytics blog.
This blog, intended for the more technically minded readers,
will deal with real data analysis problems and their solutions – mostly in R.
</description>
<item>
<title>Linear models: Pushing down and speeding up</title>
<link>http://www.quantitative-consulting.eu/blog4.html</link>
<guid>http://www.quantitative-consulting.eu/blog4.html</guid>
<description><![CDATA[<div class="posthead">
<img src="http://www.quantitative-consulting.eu/graphics17/betahatTitle.png" class="postheadimg betahat" style="vertical-align:middle;"><div class="picnote X250">

<p>Let’s start with a few observations about linear models. The usual discussion posits a target variable <code>y</code> of
length N and a design matrix <code>X</code> with p columns (of full rank, say) and N rows. The linear model equation can be written</p>

<div style="width: 99.99%; text-align: center;"><img src="http://www.quantitative-consulting.eu/graphics17/yXb.png" style="height: 2rem;"></div>

<p>and the least squares solution is obtained by projecting <code>y</code> orthogonally onto the image of <code>X</code>  giving the almost iconic formula in the title for the estimated parameters.

</p>
</div>
</div> <div class="postbody">

<p> The most common case – unless you are a geneticist –
is that <code>X</code> is ‘long’, i.e. we have N &gt;&gt; p. We can test some properties of our least squares solution in this case in a little simulation</p>

<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r">p =<span class="st"> </span> <span class="dv">1000</span>
N =<span class="st"> </span><span class="dv">10</span>^<span class="dv">5</span>
beta =<span class="st"> </span><span class="kw">runif</span>(p, -<span class="dv">20</span>, <span class="dv">20</span>)

X &lt;-<span class="st"> </span><span class="kw">matrix</span>(<span class="kw">rnorm</span>(p*N), <span class="dt">ncol =</span> p)
y  &lt;-<span class="st"> </span>X %*%<span class="st"> </span>beta +<span class="st"> </span><span class="kw">rnorm</span>(N, <span class="dt">sd =</span> <span class="dv">5</span>)

<span class="kw">system.time</span>(XtX &lt;-<span class="st"> </span><span class="kw">crossprod</span>(X))[<span class="dv">3</span>]</code></pre></div>
<pre><code>## elapsed
##  62.784</code></pre>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="kw">system.time</span>(Xty &lt;-<span class="st"> </span><span class="kw">drop</span>(<span class="kw">crossprod</span>(X,y)))[<span class="dv">3</span>]</code></pre></div>
<pre><code>## elapsed
##   0.308</code></pre>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="kw">system.time</span>(beta_est &lt;-<span class="st"> </span><span class="kw">solve</span>(XtX, Xty))[<span class="dv">3</span>]</code></pre></div>
<pre><code>## elapsed
##   0.355</code></pre>



<p>Classical treatments of the least squares solution focus on decomposing <code>X</code> in a suitable manner to address both, the crossproduct and the inversion. This somewhat obscures the fact that there are two distinct data steps:</p>
<ul>
<li>a ‘small data’ step: Even with our hypothetical <code>p = 1000</code> coefficients, the inversion only takes a few seconds</li>
<li>a ‘big data’ step: The <em>crossproduct</em> is what we need to worry about much more for typical large <code>X</code>!</li>
</ul>
<h3>Chunking and parallelising</h3>
<p>Our example case (large <code>X</code> with N &gt;&gt; p) is ideal for chunking and parallelising. Chunking is made easy by packages like
<code>biglm</code> and <code>speedglm</code> that provide the infrastructure for handling chunked data and for updating estimates with new chunks.
Also note that the crossproducts
are ‘embarrassingly parallel’, i.e. they can be calculated via an appropriate ‘lapply’-ification:</p>



<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="kw">library</span>(parallel)

X_chunked &lt;-<span class="st"> </span><span class="kw">lapply</span>(<span class="kw">split</span>(X, (<span class="dv">1</span>:N)%%<span class="dv">9</span>) , matrix, <span class="dt">ncol =</span> p)

<span class="kw">system.time</span>(XtX_chunked &lt;-<span class="st"> </span><span class="kw">mclapply</span>(X_chunked, crossprod, <span class="dt">mc.cores =</span> <span class="dv">3</span>))[<span class="dv">3</span>]</code></pre></div>
<pre><code>## elapsed
##  31.675</code></pre>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r">XtX2 &lt;-<span class="st"> </span><span class="dv">0</span>; for(xtx in XtX_chunked) XtX2 &lt;-<span class="st"> </span>XtX2 +<span class="st"> </span>xtx
<span class="kw">sum</span>(<span class="kw">abs</span>(XtX-<span class="st"> </span>XtX2)) ## ~ 0</code></pre></div>

<p>So, chunking and parallelising helps.</p>
<p>To improve things further, one needs to look more closely at the structure of <code>X</code>. One well-known approach is in the <code>MatrixModels</code>-package, which allows to make use of sparsity in <code>X</code>, for instance, when <code>X</code> contains many dummy variables.</p>


<h3>Special structures in <code>X</code> – star schema</h3>
<p>The situation for which I have not immediately found an adequate package, and which I want to discuss in a bit more detail here, is when <code>X</code> is constructed from some kind of database ‘star schema’. As an example, we can take the fuel price data discussed <a href="blog3.html"> here</a>. </p>
<p>We start with loading the required packages and by defining a small benchmarking function, which will not only measure execution times, but also give a rough idea on memory usage:</p>



<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r">## Clear all -- only if you have saved your other projects
<span class="kw">rm</span>(<span class="dt">list=</span><span class="kw">ls</span>(<span class="dt">all=</span><span class="ot">TRUE</span>))

<span class="kw">library</span>(tidyverse)
<span class="kw">library</span>(stringr)
<span class="kw">library</span>(splines)
<span class="kw">library</span>(Matrix)
<span class="kw">library</span>(MatrixModels)

## a simple benchmarker
mstest &lt;-<span class="st"> </span>function(<span class="dt">expr=</span><span class="ot">NULL</span>) {
mem &lt;-<span class="st"> </span><span class="kw">gc</span>(<span class="dt">reset =</span> <span class="ot">TRUE</span>)[<span class="dv">2</span>, <span class="kw">c</span>(<span class="dv">2</span>,<span class="dv">6</span>)]
st &lt;-<span class="st"> </span><span class="kw">proc.time</span>()
expr
mem2 &lt;-<span class="st"> </span><span class="kw">gc</span>(<span class="dt">reset =</span> <span class="ot">FALSE</span>)[<span class="dv">2</span>, <span class="kw">c</span>(<span class="dv">2</span>,<span class="dv">6</span>)] -<span class="st"> </span>mem
<span class="kw">names</span>(mem2) &lt;-<span class="st"> </span><span class="kw">c</span>(<span class="st">"A_Mem final"</span>, <span class="st">"A_Mem max"</span>)
<span class="kw">c</span>(<span class="dt">A_Time =</span><span class="kw">structure</span>(<span class="kw">proc.time</span>()-<span class="st"> </span>st, <span class="dt">class =</span> <span class="st">"proc_time"</span>)[<span class="dv">1</span>:<span class="dv">3</span>],  mem2)
}</code></pre></div>
<p>Now load (and clean) the fuel price data (find it on GitHub  <a href="https://github.com/borva/lmDecomp1"> here</a>). It is a very simple star schema, with fuel prices per station and time as fact table:</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r">pricesAll &lt;-<span class="st"> </span><span class="kw">readRDS</span>( <span class="st">"Prices_Demo.rds"</span>)%&gt;%
<span class="st">  </span><span class="kw">filter</span>(E10 &gt;<span class="st"> </span><span class="dv">700</span>, E10 &lt;<span class="st"> </span><span class="dv">3500</span>, TimeAggID &gt;<span class="st"> </span><span class="dv">26425</span>,
## choose TimeAggID filter to fit to your machine
!<span class="kw">is.na</span>(CompE10))
pricesAll</code></pre></div>
<pre><code>##    StationID TimeAggID   E10 CompE10
##        &lt;int&gt;     &lt;int&gt; &lt;int&gt;   &lt;int&gt;
##  1         1     26426  1269    1450
##  2         1     26427  1269    1450
##  3         1     26428  1269    1450
##  4         1     26429  1269    1450
##  5         1     26430  1269    1439
## # ... with 4,859,833 more rows</code></pre>
<p>as well as dimension tables for stations and times:</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r">timesAll &lt;-<span class="st"> </span><span class="kw">readRDS</span>( <span class="st">"E_prtimes.rds"</span>)
timesAll</code></pre></div>
<pre><code>##    TimeAggID DateHour DateDay HourCl  DayCl Brent
##        &lt;int&gt;    &lt;int&gt;   &lt;int&gt; &lt;fctr&gt; &lt;fctr&gt; &lt;int&gt;
##  1         1 14060800  140608 Hour00    Sun   501
##  2         2 14060801  140608 Hour01    Sun   501
##  3         3 14060802  140608 Hour02    Sun   501
##  4         4 14060803  140608 Hour03    Sun   501
##  5         5 14060804  140608 Hour04    Sun   501

## # ... with 27,523 more rows</code></pre>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r">stationsAll &lt;-<span class="st"> </span><span class="kw">readRDS</span>( <span class="st">"C_stationsAll_final.rds"</span>)

## add natural splines to stations
NS &lt;-<span class="st"> </span><span class="kw">as_data_frame</span>( <span class="kw">model.matrix</span>( ~<span class="st"> </span>-<span class="dv">1</span> +<span class="st"> </span><span class="kw">ns</span>(lat, <span class="dt">df =</span> <span class="dv">3</span>):<span class="kw">ns</span>(lng, <span class="dt">df =</span> <span class="dv">3</span>),
<span class="dt">data =</span> stationsAll ))

<span class="kw">names</span>(NS) &lt;-<span class="st"> </span><span class="kw">paste0</span>(<span class="st">"NS"</span>,<span class="kw">str_replace_all</span>(<span class="kw">names</span>(NS),
<span class="st">"</span><span class="ch">\\</span><span class="st">:|ns</span><span class="ch">\\</span><span class="st">(lat, df = </span><span class="ch">\\</span><span class="st">d+</span><span class="ch">\\</span><span class="st">)|ns</span><span class="ch">\\</span><span class="st">(lng, df = </span><span class="ch">\\</span><span class="st">d+</span><span class="ch">\\</span><span class="st">)"</span>, <span class="st">""</span>))
stationsAll &lt;-<span class="st"> </span><span class="kw">bind_cols</span>(stationsAll, NS)
stationsAll</code></pre></div>
<pre><code>##    StationID brandCl       lng      lat isBAB closeBAB       NS11
##        &lt;int&gt;  &lt;fctr&gt;     &lt;dbl&gt;    &lt;dbl&gt; &lt;int&gt;    &lt;int&gt;      &lt;dbl&gt;
##  1         1  Others 10.850848 48.55568     0        0 0.39713860
##  2         2     BfT 10.920224 49.66159     0        0 0.43709986
##  3         3  Others  6.948950 51.16919     0        0 0.01966565
##  4         4  Others 11.451392 48.12189     0        1 0.37167161
##  5         5  Others 12.520820 48.24147     0        0 0.28931168
## # ... with 14,897 more rows, and 8 more variables: NS21 &lt;dbl&gt;, NS31 &lt;dbl&gt;,
## #   NS12 &lt;dbl&gt;, NS22 &lt;dbl&gt;, NS32 &lt;dbl&gt;, NS13 &lt;dbl&gt;, NS23 &lt;dbl&gt;, NS33 &lt;dbl&gt;</code></pre>



<h3>Traditional approach: One big design matrix <code>X</code>
</h3>
<p>Now, let’s say we want to estimate the influence of</p>
<ul>
<li>the brand of the station</li>
<li>the closeness of the station to a highway (via isBAB, closeBAB)</li>
<li>the location of the station in Germany (via the natural splines on long / lat)</li>
<li>the time of day</li>
<li>the average price of Competitors (CompE10 – I’ll say more about this, later)</li>
</ul>
<p>etc. on the price of E10 fuel.</p>
<p>In the traditional approach, we join all the dimension information to the fact table and run the model on the resulting large table:</p>



<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r">fulldat &lt;-<span class="st"> </span>pricesAll %&gt;%
<span class="st">  </span><span class="kw">left_join</span>(<span class="kw">select</span>(timesAll, -DateHour, -DateDay )) %&gt;%
<span class="st">  </span><span class="kw">left_join</span>(stationsAll)

<span class="kw">object.size</span>(fulldat)/<span class="dv">10</span>^<span class="dv">6</span> ## 622MB

RESULT &lt;-<span class="st"> </span><span class="ot">NULL</span>

modfor &lt;-<span class="st"> </span><span class="kw">as.formula</span>(
<span class="kw">paste0</span>(<span class="st">"E10 ~ 1 +  CompE10 + Brent + isBAB + closeBAB + brandCl +"</span>,
<span class="st">"DayCl  +  HourCl +"</span>,
<span class="kw">paste</span>(<span class="kw">names</span>(NS), <span class="dt">collapse =</span> <span class="st">" + "</span>)))

msLM &lt;-<span class="st"> </span><span class="kw">mstest</span>(modLM &lt;-<span class="st"> </span><span class="kw">lm</span>( modfor, <span class="dt">data =</span> fulldat))

RESULT[[<span class="st">"trad. LM"</span>]] &lt;-<span class="st"> </span><span class="kw">c</span>(msLM, modLM$coefficients)
msLM</code></pre></div>
<pre><code>## A_Time.user.self  A_Time.sys.self   A_Time.elapsed      A_Mem final
##           41.343            0.854           42.315         2870.500
##        A_Mem max
##         5058.200</code></pre>





<h3>Exploiting the star schema: Lifted matrices</h3>
<p>So, how to make this smaller and faster?</p>
<p>The main observation is that the parts of the design matrix, that come from the joined dimension matrices, have a very simple form. For example, when looking at the variables which depend on time only:</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"> matTime =<span class="st"> </span><span class="kw">model.Matrix</span>(~<span class="st"> </span>-<span class="dv">1</span> +<span class="st"> </span> Brent + DayCl + HourCl, <span class="dt">data =</span> timesAll )</code></pre></div>
<p>is the design matrix on the table <code>timesAll</code> and</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r">indTime =<span class="st"> </span><span class="kw">as</span>(<span class="kw">list</span>(pricesAll$TimeAggID, <span class="kw">max</span>(timesAll$TimeAggID)), <span class="st">"indMatrix"</span>)</code></pre></div>
<p>is the (sparse version of) the ‘index matrix’, representing the join. This matrix has a 1 in position <code>(ro, co)</code> exactly when <code>TimeAggID[ro] == co</code> and zeros otherwise. It is easy to check that the matrix product of <code>indTime</code> and <code>matTime</code>
is the lift / join of <code>matTime</code> to the fact table</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="kw">all</span>(indTime %*%<span class="st"> </span>matTime ==<span class="st"> </span>matTime[pricesAll$TimeAggID, ]) ## TRUE</code></pre></div>
<p>This is a very useful representation, as</p>

<ol>
<li> matTime will be comparatively small,</li>
<li> crossproducts with the index matrix 'indTime' amount to a simple summing over groups, and need to be executed only once, regardless the size of matTime</li>
</ol>
<p>Furthermore, index matrix algebra is already implemented in the <code>Matrix</code>-package.</p>
<p>Let’s call these objects ‘lifted matrices’. We can actually define them as a simple extension of the classes in <code>Matrix</code>:</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="kw">setClass</span>(<span class="st">"liftMatrix"</span>,
<span class="kw">representation</span>(<span class="dt">mat =</span> <span class="st">"Matrix"</span>,
<span class="dt">indI  =</span> <span class="st">"indMatrix"</span>))</code></pre></div>
<p>The beauty of the ‘Matrix’-package (and the S4-system it is built on) is that we now only need to implement the algebra for this new class as a set of S4-methods,
adding to (in one case for the moment: overriding) the existing method-definitions in <code>Matrix</code>:</p>



<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r">## changes some 'Matrix'-definitions. Restart R afterwards

<span class="kw">setMethod</span>(<span class="st">"crossprod"</span>, <span class="kw">signature</span>( <span class="dt">x =</span> <span class="st">"indMatrix"</span>, <span class="dt">y =</span> <span class="st">"missing"</span>),
function(x)  <span class="kw">Diagonal</span>(<span class="dt">x =</span> <span class="kw">tabulate</span>(x@perm, x@Dim[<span class="dv">2</span>])))

<span class="kw">setMethod</span>(<span class="st">"crossprod"</span>, <span class="kw">signature</span>( <span class="dt">x =</span> <span class="st">"indMatrix"</span>, <span class="dt">y =</span> <span class="st">"indMatrix"</span> ),
function(x, y) {
l1 &lt;-<span class="st"> </span><span class="kw">as</span>(x, <span class="st">"lMatrix"</span>)
l2 &lt;-<span class="st"> </span><span class="kw">as</span>(y, <span class="st">"lMatrix"</span>)
<span class="kw">crossprod</span>(l1,l2)
})

<span class="kw">setMethod</span>(<span class="st">"crossprod"</span>, <span class="kw">signature</span>( <span class="dt">x =</span> <span class="st">"liftMatrix"</span>, <span class="dt">y =</span> <span class="st">"missing"</span>),
function(x) <span class="kw">crossprod</span>(x@mat, <span class="kw">crossprod</span>(<span class="kw">crossprod</span>(x@indI) , x@mat)))

<span class="kw">setMethod</span>(<span class="st">"crossprod"</span>, <span class="kw">signature</span>( <span class="dt">x =</span> <span class="st">"liftMatrix"</span>, <span class="dt">y =</span> <span class="st">"liftMatrix"</span> ),
function(x, y)   <span class="kw">crossprod</span>(x@mat,
<span class="kw">crossprod</span>(<span class="kw">crossprod</span>(y@indI, x@indI), y@mat)))

<span class="kw">setMethod</span>(<span class="st">"crossprod"</span>, <span class="kw">signature</span>( <span class="dt">x =</span> <span class="st">"liftMatrix"</span>, <span class="dt">y =</span> <span class="st">"Matrix"</span> ),
function(x, y)   {
<span class="kw">crossprod</span>(x@mat, <span class="kw">crossprod</span>(x@indI, y)) })

<span class="kw">setMethod</span>(<span class="st">"crossprod"</span>, <span class="kw">signature</span>( <span class="dt">x =</span> <span class="st">"Matrix"</span>, <span class="dt">y =</span> <span class="st">"liftMatrix"</span> ),
function(x, y)   {
<span class="kw">crossprod</span>(x, y@indI) %*%<span class="st"> </span>y@mat })</code></pre></div>

<p>With these definitions, it is now easy to define the ‘lifted’ (or ‘pushed down’, depending on your point of view) version of our fuel price model above, by  separately defining the components of the design which stem from the two dimension tables and (for the effect of <code>CompE10</code>) from the fact table itself.</p>
<p>I go through the full calculation here for demonstration purposes. I hope to put this into a more user-friendly format, soon.</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r">msLift &lt;-<span class="st"> </span><span class="kw">mstest</span>({

modforS &lt;-<span class="st"> </span><span class="kw">as.formula</span>(
<span class="kw">paste0</span>(<span class="st">"~ 1 +  isBAB + closeBAB + brandCl +"</span>,
<span class="kw">paste</span>(<span class="kw">names</span>(NS), <span class="dt">collapse =</span> <span class="st">" + "</span>)))

XS &lt;-<span class="st"> </span><span class="kw">new</span>(<span class="st">"liftMatrix"</span>,
<span class="dt">mat =</span> <span class="kw">model.Matrix</span>(modforS, <span class="dt">data =</span> stationsAll )*<span class="fl">1.0</span>,
<span class="dt">indI =</span> <span class="kw">as</span>(<span class="kw">list</span>(pricesAll$StationID, <span class="kw">max</span>(stationsAll$StationID)),
<span class="st">"indMatrix"</span>))

modforT &lt;-<span class="st"> </span><span class="kw">as.formula</span>(<span class="kw">paste0</span>(<span class="st">"~ 1 + Brent + DayCl + HourCl"</span>))

XT &lt;-<span class="st"> </span><span class="kw">new</span>(<span class="st">"liftMatrix"</span>,
<span class="dt">mat =</span> <span class="kw">model.Matrix</span>(modforT, <span class="dt">data =</span> timesAll )[,-<span class="dv">1</span>]*<span class="fl">1.0</span>,
<span class="dt">indI =</span> <span class="kw">as</span>(<span class="kw">list</span>(pricesAll$TimeAggID, <span class="kw">max</span>(timesAll$TimeAggID)),
<span class="st">"indMatrix"</span>))

XC  &lt;-<span class="st"> </span><span class="kw">Matrix</span>( pricesAll$CompE10, <span class="dt">ncol =</span> <span class="dv">1</span>,
<span class="dt">dimnames =</span> <span class="kw">list</span>(<span class="ot">NULL</span>, <span class="st">"CompE10"</span>))

Y &lt;-<span class="st"> </span><span class="kw">Matrix</span>(pricesAll$E10, <span class="dt">ncol =</span> <span class="dv">1</span>)

XTXT &lt;-<span class="st"> </span><span class="kw">crossprod</span>(XT)
XSXS &lt;-<span class="st"> </span><span class="kw">crossprod</span>(XS)
XCXC &lt;-<span class="st"> </span><span class="kw">crossprod</span>(XC)
XTXS &lt;-<span class="st"> </span><span class="kw">crossprod</span>(XT, XS)
XTXC &lt;-<span class="st"> </span><span class="kw">crossprod</span>(XT, XC)
XSXC &lt;-<span class="st"> </span><span class="kw">crossprod</span>(XS, XC)
XSY &lt;-<span class="st"> </span><span class="kw">crossprod</span>(XS, Y)
XTY &lt;-<span class="st"> </span><span class="kw">crossprod</span>(XT, Y)
XCY &lt;-<span class="st"> </span><span class="kw">crossprod</span>(XC, Y)

XX &lt;-<span class="st">  </span><span class="kw">rbind</span>(<span class="kw">cbind</span>(XTXT, XTXS, XTXC),
<span class="kw">cbind</span>(<span class="kw">t</span>(XTXS), XSXS, XSXC),
<span class="kw">cbind</span>(<span class="kw">t</span>(XTXC), <span class="kw">t</span>(XSXC), XCXC))
XY &lt;-<span class="st"> </span><span class="kw">rbind</span>(XTY, XSY, XCY)

modLift &lt;-<span class="st"> </span><span class="kw">drop</span>(<span class="kw">solve</span>(XX, XY))
})

RESULT[[<span class="st">"lifted LM"</span>]] &lt;-<span class="st"> </span><span class="kw">c</span>(modLift,  msLift)</code></pre></div>

<p>
A bit of arranging of the results for easier comparison:
</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r">for(nam in <span class="kw">names</span>(RESULT)) RESULT[[nam]]&lt;-<span class="st"> </span>
<span class="st">  </span><span class="kw">data.frame</span>( <span class="dt">estimate =</span> RESULT[[nam]]) %&gt;%<span class="st"> </span>
<span class="st">  </span><span class="kw">rownames_to_column</span>(<span class="dt">var =</span> <span class="st">"term"</span>) %&gt;%
<span class="st">  </span><span class="kw">mutate</span>(<span class="dt">model =</span> nam)

resultWide &lt;-<span class="st"> </span><span class="kw">bind_rows</span>(RESULT) %&gt;%<span class="st"> </span>dplyr::<span class="kw">select</span>(model, term, estimate) %&gt;%
<span class="st">  </span><span class="kw">spread</span>(model, estimate)

<span class="kw">head</span>(resultWide, <span class="dv">10</span>)</code></pre></div>
<pre><code>##                term   lifted LM    trad. LM
## 1       A_Mem final   84.000000 2870.500000
## 2         A_Mem max 2103.000000 5058.200000
## 3    A_Time.elapsed    3.510000   42.315000
## 4   A_Time.sys.self    0.204000    0.854000
## 5  A_Time.user.self    3.291000   41.343000
## 6       brandClAral   23.329966   23.329966
## 7       brandClAvia   -5.360235   -5.360235
## 8        brandClBfT  -17.300784  -17.300784
## 9       brandClEsso   -3.675214   -3.675214
## 10       brandClHEM  -20.194030  -20.194030</code></pre>

<p> Four seconds instead of forty – Pretty impressive, huh?</p>
<p>Well, of course, I have massaged the example a bit. The model we have been looking at is a pretty extreme case. Almost all the explanatory variables are ‘lifts’ from one of the dimension tables. So the model is almost a product of two completely separate models. I actually had to sneak in the variable ‘CompE10’ (with all the problems, endogeneity, inconsistency, this variable brings, were we to really try to interpret this model) in order to make the example a truly non-product one.</p>
<p>Still, this approach is worthwile in many cases, and I will soon publish a more elaborate example, including how to deal with chunked and partitioned data, as well as allowing fixed effects.</p>
<p>So stay tuned!</p>
</div>]]></description>
<pubDate>Sat, 21 Oct 2017 00:00:00 GMT</pubDate>
<author>bvaillant@quantitative-consulting.eu (Boris Vaillant)</author>
</item>
<item>
<title>The German fuel prices data set</title>
<link>http://www.quantitative-consulting.eu/blog3.html</link>
<guid>http://www.quantitative-consulting.eu/blog3.html</guid>
<description><![CDATA[<div class="posthead">
<img src="http://www.quantitative-consulting.eu/graphics17/geoPlot_Blog3.png" class="postheadimg"><div class="picnote X250">

<p>The data set on German fuel prices contains the fuel prices, but not the sales, from more than 14000 fuel stations in Germany since June 2014. It is made available by the webservice <a href="http://www.tankerkoenig.de"> Tankerkoenig </a> as a Postgres dump (from June 2014 onwards) under CC4.0.</p>
</div>
</div> <div class="postbody">
<p>This is a particularly interesting data set</p>
<ul>
<li>
<p>from the general public point of view as</p>
<ul>
<li>it deals with a topic under strong public scrutiny and is already intensively studied by economists</li>
<li>the data is also constantly updated and allows for continuous monitoring for changes in trends or new phenomena</li>
</ul>
</li>
<li>
<p>from the data science point of view as</p>
<ul>
<li>this is a real life data set with all the little quirks and bugs whose correction forms large part of an analysts working hours</li>
<li>the data is small enough (~ 3GB in the original data dump) to be effectively prepared and analysed on a single computer, but big enough to allow to test different techniques for scaling and speeding up the analysis in a cluster</li>
<li>it allows for the integration of many other (open) data sources (socio-economic data, weather, traffic, holidays). See the graph below.</li>
<li>interesting results can already be obtained using purely descriptive methods, but the data can also be analysed and modelled under spatial–, time series–, panel– and many other aspects.</li>
</ul>
</li>
</ul>
<h3>Overview of the available data and structure</h3>
<br><embed src="http://www.quantitative-consulting.eu/graphics17/G_DataStructure.svg" type="image/svg+xml" style="width: 99.99%;  text-align: center;"></embed><p> The original data is available at
<a href="https://creativecommons.tankerkoenig.de/">Tankerkoenig</a>, the current status of the code for the data preparation,
some of the additional external data, and some simple first models are available as a “workshop” at my <a href="https://github.com/borva/fuel">GitHub-account</a>.</p>

<h3> Structure of the GitHub project </h3>
<ol style="list-style-type: none;">
<li>
<h4 style="text-align: left;"> A) Collection of regional data tables from destatis</h4>
<p>Reading, cleaning and consolidating multiple socio-demographic data files</p>
</li>
<li>
<h4 style="text-align: left;"> B) Preparation and cleaning of the fuel station master data</h4>
<p>Tidying, creation of brand and highway markers using regular expressions, parsing of json-information on opening hours</p>
</li>
<li>
<h4 style="text-align: left;">C) Geo-operations on the station master</h4>
<p>Identification of NUTS 3-region per station, station distance matrices to competitors, highways, traffic-counters etc.
</p>
</li>
<li>
<h4 style="text-align: left;">D) Preparation of price data</h4>
<p>
Reading from Postgres, cleaning strange prices, imputing and aggregating the price data (see also the blog entry about <a href="blog1.html"> efficient missing line imputation</a>). Calculation of competitor prices
</p>
</li>

<li>
<h4 style="text-align: left;">E) Creation of models</h4>
<p>
Moving to AWS, test of different  (Linear, Panel, Spatial) models, collection of results
</p>
</li>
<li><h4 style="text-align: left;">F) Analyses, preparation and visualisation of results</h4></li>
<li><h4 style="text-align: left;">G) Presentation creation (not yet on GitHub)</h4></li>
</ol>
<br><p>You can find the print-version of my UseR!2017-talk on this project <a href="material17/Presentation_BV_FuelPrices_UseR_170712_V19.pdf">here</a>. There is also a video, courtesy of Channel 9, that you can watch here:</p>
<iframe src="https://channel9.msdn.com/Events/useR-international-R-User-conferences/useR-International-R-User-2017-Conference/Analysis-of-German-Fuel-Prices-with-R/player" width="99.9%" max-width="960" height="540" allowfullscreen frameborder="0">
</iframe>
<p></p>
<br>
</div>]]></description>
<pubDate>Fri, 28 Jul 2017 00:00:00 GMT</pubDate>
<author>bvaillant@quantitative-consulting.eu (Boris Vaillant)</author>
</item>
<item>
<title>A simple static website generator with purrr</title>
<link>http://www.quantitative-consulting.eu/blog2.html</link>
<guid>http://www.quantitative-consulting.eu/blog2.html</guid>
<description><![CDATA[<div class="posthead">
<img src="http://www.quantitative-consulting.eu/graphics17/WORLD_Full_T200X200.png" class="postheadimg"><div class="picnote X250">

<p>Today, I want to present a simple way to use <code>purrr</code> to create a static website generator. Of course, there is Jekyll, Hugo and the <code>blogdown</code> package, but in many cases you may find yourself, like I did, with your own bits and pieces of html, no time to learn yet another language, and in need of a way to put all this into a structured and consistent static website.</p>

</div>
</div> <div class="postbody">
<p>The approach I took is</p>
<ul>
<li>keep all the website elements in one large html file, the “master page” (a collection of files works too)</li>
<li>use html comments to define the start and end of the different sections, of which the different pages of the website will be composed</li>
<li>define all links using hrefs on #ids</li>
</ul>
<p>and write a <code>R</code> /<code>purrr</code>-script to</p>
<ul>
<li>manage the recombination of the sections onto different pages</li>
<li>replace all href-attributes with correct link addresses</li>
</ul>
<p>To show how this works, assume our “master page” looks like this</p>
<div class="sourceCode"><pre class="sourceCode html"><code class="sourceCode html"><span class="co">&lt;!-- START_HEADER --&gt;</span>
<span class="dt">&lt;!DOCTYPE </span>html<span class="dt">&gt;</span>
<span class="kw">&lt;html&gt;&lt;head&gt;</span>
<span class="kw">&lt;style</span><span class="ot"> type=</span><span class="st">"text/css"</span><span class="kw">&gt;</span>

body, html <span class="kw">{height:</span> <span class="dt">100%</span><span class="kw">;}</span>
<span class="fl">.A</span> <span class="kw">{</span> <span class="kw">border:</span> <span class="dt">2px</span> <span class="dt">solid</span> orange<span class="kw">;</span> <span class="kw">height:</span> <span class="dt">30%</span><span class="kw">;</span> <span class="kw">width:</span> <span class="dt">60%</span><span class="kw">;}</span>
<span class="fl">.B</span> <span class="kw">{</span> <span class="kw">background-color:</span> darkorange <span class="kw">;</span> <span class="kw">height:</span> <span class="dt">80%</span><span class="kw">;</span> <span class="kw">width:</span> <span class="dt">60%</span><span class="kw">;}</span>
<span class="fl">.C</span> <span class="kw">{</span> <span class="kw">border:</span> <span class="dt">2px</span> <span class="dt">solid</span> lightblue<span class="kw">;</span> <span class="kw">height:</span> <span class="dt">90%</span><span class="kw">;</span> <span class="kw">width:</span> <span class="dt">60%</span><span class="kw">;}</span>
<span class="fl">.D</span> <span class="kw">{</span> <span class="kw">background-color:</span> steelblue <span class="kw">;</span> <span class="kw">height:</span> <span class="dt">70%</span><span class="kw">;</span> <span class="kw">width:</span> <span class="dt">60%</span><span class="kw">;}</span>

<span class="fl">.navbar</span> <span class="kw">{width:</span> <span class="dt">60%</span><span class="kw">;</span> <span class="kw">background-color:</span> grey<span class="kw">;</span> <span class="kw">position:</span> <span class="dt">fixed</span><span class="kw">;</span> <span class="kw">top:</span> <span class="dt">0</span><span class="kw">;}</span>

a <span class="kw">{</span> <span class="kw">display:</span> <span class="dt">inline-block</span><span class="kw">;</span> <span class="kw">padding:</span> <span class="dt">0.5rem</span><span class="kw">;}</span>
<span class="kw">&lt;/style&gt;</span>
<span class="kw">&lt;/head&gt;</span>
<span class="co">&lt;!-- END_HEADER --&gt;</span>
<span class="co">&lt;!-- START_TOP --&gt;</span>
<span class="kw">&lt;body&gt;</span>
<span class="kw">&lt;div</span><span class="ot"> class=</span><span class="st">"navbar"</span><span class="kw">&gt;</span>
<span class="kw">&lt;a</span><span class="ot"> href=</span><span class="st">"#HOME"</span><span class="kw">&gt;</span> Home <span class="kw">&lt;/a&gt;</span>
<span class="kw">&lt;a</span><span class="ot"> href=</span><span class="st">"#BB"</span><span class="kw">&gt;</span> Link to BB<span class="kw">&lt;/a&gt;</span>
<span class="kw">&lt;a</span><span class="ot"> href=</span><span class="st">"#CC"</span><span class="kw">&gt;</span> Link to CC<span class="kw">&lt;/a&gt;</span>
<span class="kw">&lt;/div&gt;</span>
<span class="kw">&lt;br&gt;</span>
<span class="kw">&lt;br&gt;</span>
<span class="kw">&lt;h1&gt;</span> My website <span class="kw">&lt;/h1&gt;</span>
<span class="kw">&lt;hr&gt;</span>
<span class="co">&lt;!-- END_TOP --&gt;</span>
<span class="co">&lt;!-- START_AA --&gt;</span>
<span class="kw">&lt;div</span><span class="ot"> class=</span><span class="st">"A"</span><span class="kw">&gt;</span>
<span class="kw">&lt;h3&gt;</span> AA - Intro material<span class="kw">&lt;/h3&gt;</span>
<span class="kw">&lt;a</span><span class="ot"> href=</span><span class="st">"#DD"</span><span class="kw">&gt;</span> LINK to DD <span class="kw">&lt;/a&gt;</span>
<span class="kw">&lt;/div&gt;</span>
<span class="co">&lt;!-- END_AA --&gt;</span>
<span class="co">&lt;!-- START_BB --&gt;</span>
<span class="kw">&lt;div</span><span class="ot"> id=</span><span class="st">"BB"</span><span class="kw">&gt;</span> <span class="kw">&lt;/div&gt;</span>
<span class="kw">&lt;br&gt;</span>
<span class="kw">&lt;br&gt;</span>
<span class="kw">&lt;div</span><span class="ot"> class=</span><span class="st">"B"</span><span class="kw">&gt;</span>
<span class="kw">&lt;h3&gt;</span>Section BB<span class="kw">&lt;/h3&gt;</span>
<span class="kw">&lt;a</span><span class="ot"> href=</span><span class="st">"#CC"</span><span class="kw">&gt;</span> LINK to CC <span class="kw">&lt;/a&gt;</span>
<span class="kw">&lt;/div&gt;</span>
<span class="co">&lt;!-- END_BB --&gt;</span>
<span class="co">&lt;!-- START_CC --&gt;</span>
<span class="kw">&lt;div</span><span class="ot"> id=</span><span class="st">"CC"</span><span class="kw">&gt;</span> <span class="kw">&lt;/div&gt;</span>
<span class="kw">&lt;br&gt;</span>
<span class="kw">&lt;br&gt;</span>
<span class="kw">&lt;div</span><span class="ot"> class=</span><span class="st">"C"</span><span class="kw">&gt;</span>
<span class="kw">&lt;h3&gt;</span>Section CC<span class="kw">&lt;/h3&gt;</span>
<span class="kw">&lt;a</span><span class="ot"> href=</span><span class="st">"#BB"</span><span class="kw">&gt;</span> LINK to BB <span class="kw">&lt;/a&gt;</span>
<span class="kw">&lt;/div&gt;</span>
<span class="co">&lt;!-- END_CC --&gt;</span>
<span class="co">&lt;!-- START_DD --&gt;</span>
<span class="kw">&lt;div</span><span class="ot"> id=</span><span class="st">"DD"</span><span class="kw">&gt;</span> <span class="kw">&lt;/div&gt;</span>
<span class="kw">&lt;br&gt;</span>
<span class="kw">&lt;br&gt;</span>
<span class="kw">&lt;div</span><span class="ot"> class</span> <span class="ot">=</span> <span class="st">"D"</span><span class="kw">&gt;</span>
<span class="kw">&lt;h3&gt;</span>DD - Some other content <span class="kw">&lt;/h3&gt;</span>
<span class="kw">&lt;a</span><span class="ot"> href=</span><span class="st">"#BB"</span><span class="kw">&gt;</span> LINK to BB <span class="kw">&lt;/a&gt;</span>
<span class="kw">&lt;a</span><span class="ot"> href=</span><span class="st">"#CC"</span><span class="kw">&gt;</span> LINK to CC <span class="kw">&lt;/a&gt;</span>
<span class="kw">&lt;/div&gt;</span>
<span class="co">&lt;!-- END_DD --&gt;</span>
<span class="kw">&lt;/body&gt;</span> <span class="kw">&lt;/html&gt;</span></code></pre></div>
<p>This html contains all the parts we need to piece together our website. All we do here is to mark each of our sections with html-comments à la <code>&lt;!-- START_DD --&gt;</code>. For simplicity, we also place and name our id-attributes accordingly. Also, usually, we would keep the CSS in a separate file.</p>
<p>Now, let’s say we want a front page with intro material A and one page each for the material in sections B and C+D.</p>
<p>We start by reading the file into a nested data frame, one nest for each of the sections we have defined</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="kw">library</span>(tidyverse)
<span class="kw">library</span>(stringr)

PATHOUT =<span class="st"> "./Site/"</span>
fildat &lt;-<span class="st"> </span><span class="kw">readLines</span>(<span class="st">"masterpage.html"</span>)

## marker for html blocks
markerdat &lt;-<span class="st"> </span><span class="kw">tibble</span>(
<span class="dt">markerline =</span> fildat %&gt;%<span class="st"> </span><span class="kw">str_which</span>(<span class="st">"&lt;!-- START_|&lt;!-- END_"</span>),
<span class="dt">orig =</span> fildat[markerline],
<span class="dt">markertype =</span> <span class="kw">str_extract</span>(orig, <span class="st">"START|END"</span>),
<span class="dt">markername =</span> <span class="kw">str_replace_all</span>(orig, <span class="st">"&lt;!--| |START_|END_|--&gt;|</span><span class="ch">\\</span><span class="st">t"</span>, <span class="st">""</span>))

markerall &lt;-<span class="st"> </span>markerdat %&gt;%<span class="st"> </span><span class="kw">select</span>( -orig ) %&gt;%
<span class="st">  </span><span class="kw">spread</span>(<span class="dt">key =</span> markertype, <span class="dt">value =</span> markerline) %&gt;%
<span class="st">  </span><span class="kw">mutate</span>(<span class="dt">origlines =</span> <span class="kw">map2</span>( START, END, ~<span class="st">`</span><span class="dt">[</span><span class="st">`</span>(fildat, .x:.y))) %&gt;%
<span class="st">  </span><span class="kw">arrange</span>(START)

markerall</code></pre></div>
<pre><code>## # A tibble: 6 x 4
##   markername   END START  origlines
##        &lt;chr&gt; &lt;int&gt; &lt;int&gt;     &lt;list&gt;
## 1     HEADER    17     1 &lt;chr [17]&gt;
## 2        TOP    29    18 &lt;chr [12]&gt;
## 3         AA    35    30  &lt;chr [6]&gt;
## 4         BB    44    36  &lt;chr [9]&gt;
## 5         CC    53    45  &lt;chr [9]&gt;
## 6         DD    63    54 &lt;chr [10]&gt;</code></pre>
<p>We then define how our website should be built by declaring the order of the building blocks for each page.</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r">pagedef &lt;-<span class="st"> </span><span class="kw">list</span>(
<span class="dt">main =</span> <span class="kw">tibble</span>(
<span class="dt">filename =</span> <span class="st">"index.html"</span>,
<span class="dt">blocks =</span> <span class="kw">c</span>(<span class="st">"HEADER"</span>,
<span class="st">"&lt;style&gt; .navbar { background-color: #AAAAAA; } &lt;/style&gt;"</span>,
<span class="st">"&lt;div id = </span><span class="ch">\"</span><span class="st">HOME</span><span class="ch">\"</span><span class="st">&gt; &lt;/div&gt;"</span>,
<span class="st">"TOP"</span>,
<span class="st">"AA"</span>,
<span class="st">"&lt;hr&gt; &lt;p&gt; A few additional remarks &lt;/p&gt; &lt;hr&gt;"</span>,
<span class="st">"&lt;/body&gt; &lt;/html&gt;"</span>) ),
<span class="dt">sectB =</span> <span class="kw">tibble</span>(
<span class="dt">filename =</span> <span class="st">"sectB.html"</span>,
<span class="dt">blocks =</span> <span class="kw">c</span>(<span class="st">"HEADER"</span>,
<span class="st">"&lt;style&gt; .navbar { background-color: #CCCCCC; } &lt;/style&gt;"</span>,
<span class="st">"TOP"</span>,
<span class="st">"BB"</span>,
<span class="st">"&lt;/body&gt; &lt;/html&gt;"</span>) ),
<span class="dt">sectCD =</span> <span class="kw">tibble</span>(
<span class="dt">filename =</span> <span class="st">"sectCD.html"</span>,
<span class="dt">blocks =</span> <span class="kw">c</span>(<span class="st">"HEADER"</span>,
<span class="st">"&lt;style&gt; .navbar { background-color: #666666; } &lt;/style&gt;"</span>,
<span class="st">"TOP"</span>,
<span class="st">"CC"</span>,
<span class="st">"DD"</span>,
<span class="st">"&lt;/body&gt; &lt;/html&gt;"</span>) ) ) %&gt;%<span class="st"> </span>
<span class="st">  </span><span class="kw">bind_rows</span>()</code></pre></div>
<p>Identifying the corresponding lines of html for each block then really becomes no more than a join-operation:</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r">pagecompile &lt;-<span class="st"> </span>pagedef  %&gt;%<span class="st"> </span>
<span class="st">  </span><span class="kw">left_join</span>(markerall, <span class="dt">by =</span> <span class="kw">c</span>(<span class="st">"blocks"</span> =<span class="st"> "markername"</span>)) %&gt;%
<span class="st">  </span><span class="kw">mutate</span>(<span class="dt">publishlines =</span>
<span class="kw">map2</span>(blocks, origlines, ~if(<span class="kw">is.null</span>(.y)) {.x} else {.y})) %&gt;%<span class="st"> </span>
<span class="st">  </span><span class="kw">select</span>(filename, publishlines)%&gt;%<span class="st"> </span>
<span class="st">  </span><span class="kw">unnest</span>() %&gt;%
<span class="st">  </span><span class="kw">nest</span>(-filename)

pagecompile</code></pre></div>
<pre><code>## # A tibble: 3 x 2
##      filename              data
##         &lt;chr&gt;            &lt;list&gt;
## 1  index.html &lt;tibble [39 x 1]&gt;
## 2  sectB.html &lt;tibble [40 x 1]&gt;
## 3 sectCD.html &lt;tibble [50 x 1]&gt;</code></pre>
<p>This defines the three html files we want for our website. It remains to make sure that the original href-attributes are adapted to this structure. We start by collecting the info on all (types of) link sources and link targets in our three website files</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r">linksrc &lt;-<span class="st"> </span>pagecompile %&gt;%
<span class="st"> </span><span class="kw">mutate</span>(<span class="dt">href =</span>  <span class="kw">map</span>(data, ~<span class="kw">str_match</span>(.$publishlines,
<span class="dt">pattern =</span> <span class="st">"href</span><span class="ch">\\</span><span class="st">s*=</span><span class="ch">\\</span><span class="st">s*</span><span class="ch">\"</span><span class="st">(#[A-Z0-9_]*)</span><span class="ch">\"</span><span class="st">"</span> )[,<span class="dv">2</span>]) %&gt;%
<span class="st">          </span><span class="kw">map</span>(~<span class="kw">unique</span>(.[!<span class="kw">is.na</span>(.)]))) %&gt;%<span class="st"> </span>
<span class="st">  </span><span class="kw">select</span>(<span class="dt">srcfile =</span> filename, href) %&gt;%
<span class="st">  </span><span class="kw">unnest</span>()

linktgt &lt;-<span class="st"> </span>pagecompile %&gt;%
<span class="st">  </span><span class="kw">mutate</span>(<span class="dt">id =</span>  <span class="kw">map</span>(data, ~<span class="kw">str_match</span>(.$publishlines,
<span class="dt">pattern =</span> <span class="st">"id</span><span class="ch">\\</span><span class="st">s*=</span><span class="ch">\\</span><span class="st">s*</span><span class="ch">\"</span><span class="st">([A-Z0-9_]*)</span><span class="ch">\"</span><span class="st">"</span> )[,<span class="dv">2</span>]) %&gt;%
<span class="st">          </span><span class="kw">map</span>(~<span class="kw">paste0</span>(<span class="st">"#"</span>, <span class="kw">unique</span>(.[!<span class="kw">is.na</span>(.)])))) %&gt;%<span class="st"> </span>
<span class="st">  </span><span class="kw">select</span>(<span class="dt">tgtfile =</span> filename, id) %&gt;%
<span class="st">  </span><span class="kw">unnest</span>()

linktgt</code></pre></div>
<pre><code>## # A tibble: 4 x 2
##       tgtfile    id
##         &lt;chr&gt; &lt;chr&gt;
## 1  index.html #HOME
## 2  sectB.html   #BB
## 3 sectCD.html   #CC
## 4 sectCD.html   #DD</code></pre>
<p>We would be in trouble if an <code>id</code>-attribute appeared more than once in the <code>linktgt</code>-table. This could happen if we wanted to reuse some of our html-blocks on several pages. In that case, we would have to introduce an additional rule, which of the copies should be considered as the true target for links.</p>
<p>For our little demonstration here, I have avoided this and other complexities. One additional rule, however, already needs taking care of in our example: On pages like <code>sectB.html</code>, whose content is exclusively from our block B, we would not want the link to jump to the id in the middle of the page. Rather, in that case, it seems more appropriate to link to the top of the page. Let’s have a look at the resulting link-structure:</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r">link2top &lt;-<span class="st"> </span><span class="kw">c</span>(<span class="st">"#BB"</span>, <span class="st">"#HOME"</span>)

linkInOut &lt;-<span class="st"> </span>linksrc %&gt;%<span class="st"> </span>
<span class="st">  </span><span class="kw">full_join</span>(linktgt, <span class="dt">by =</span> <span class="kw">c</span>(<span class="st">"href"</span> =<span class="st"> "id"</span>)) %&gt;%
<span class="st">  </span><span class="kw">mutate</span>(<span class="dt">finalLinkName =</span> <span class="kw">paste0</span>(<span class="kw">ifelse</span>(srcfile ==<span class="st"> </span>tgtfile, <span class="st">""</span>, tgtfile),
<span class="kw">ifelse</span>(href %in%<span class="st"> </span>link2top,<span class="st">""</span>, href )))%&gt;%
<span class="st">  </span><span class="kw">select</span>(srcfile, href, finalLinkName)

linkInOut </code></pre></div>
<pre><code>## # A tibble: 10 x 3
##        srcfile  href  finalLinkName
##          &lt;chr&gt; &lt;chr&gt;          &lt;chr&gt;
##  1  index.html #HOME
##  2  index.html   #BB     sectB.html
##  3  index.html   #CC sectCD.html#CC
##  4  index.html   #DD sectCD.html#DD
##  5  sectB.html #HOME     index.html
##  6  sectB.html   #BB
##  7  sectB.html   #CC sectCD.html#CC
##  8 sectCD.html #HOME     index.html
##  9 sectCD.html   #BB     sectB.html
## 10 sectCD.html   #CC            #CC</code></pre>
<br><p>Now, all that remains to be done is to replace the href-attributes and to write out the resulting html-files. In a real life application you may have to work a little more to avoid mismatches. Also, other features, like automatically updated navigation menus when you add a blog entry etc., require a little extra.
But the overall procedure seems sound and a version of this program produces the (small) website you are just looking at, in a matter of seconds.</p>
<br><div class="sourceCode">
<pre class="sourceCode r"><code class="sourceCode r">## prepare replacement pattern
linkInOut &lt;-<span class="st"> </span>linkInOut %&gt;%<span class="st"> </span>
<span class="st">  </span><span class="kw">group_by</span>(srcfile) %&gt;%<span class="st"> </span><span class="kw">nest</span>() %&gt;%
<span class="st">  </span><span class="kw">mutate</span>(<span class="dt">repPattern =</span>
<span class="kw">map</span>(data, ~<span class="kw">structure</span>(<span class="kw">paste0</span>(<span class="st">"href = </span><span class="ch">\"</span><span class="st">"</span>,.$finalLinkName),
<span class="dt">.Names =</span> <span class="kw">paste0</span>(<span class="st">"href</span><span class="ch">\\</span><span class="st">s*=</span><span class="ch">\\</span><span class="st">s*</span><span class="ch">\"</span><span class="st">"</span>,.$href)))) %&gt;%
<span class="st">  </span><span class="kw">select</span>(-data)

## run replacements on data
pagecompile &lt;-<span class="st"> </span>pagecompile %&gt;%<span class="st"> </span>
<span class="st">  </span><span class="kw">left_join</span>(linkInOut, <span class="dt">by =</span> <span class="kw">c</span>(<span class="st">"filename"</span> =<span class="st"> "srcfile"</span>)) %&gt;%
<span class="st">  </span><span class="kw">mutate</span>(<span class="dt">dataTrans =</span> <span class="kw">map2</span>(data, repPattern,
~<span class="kw">str_replace_all</span>(.x$publishlines, .y)))

## write out pages
pagecompile &lt;-<span class="st"> </span>pagecompile %&gt;%
<span class="st">  </span><span class="kw">mutate</span>( <span class="dt">fullname =</span> <span class="kw">paste0</span>(PATHOUT, filename),
<span class="dt">written =</span> <span class="kw">map2</span>(fullname, dataTrans, ~<span class="kw">writeLines</span>(.y, .x) ))</code></pre>
</div>
</div>]]></description>
<pubDate>Thu, 27 Jul 2017 00:00:00 GMT</pubDate>
<author>bvaillant@quantitative-consulting.eu (Boris Vaillant)</author>
</item>
<item>
<title>Efficient missing line imputation using the rep function</title>
<link>http://www.quantitative-consulting.eu/blog1.html</link>
<guid>http://www.quantitative-consulting.eu/blog1.html</guid>
<description><![CDATA[<div class="posthead">
<img src="http://www.quantitative-consulting.eu/graphics17/IMP_ImputePrices200X180.png" class="postheadimg"><div class="picnote X250">

<p>
To get this R blog series started, I want to present a little data preparation procedure which
comes up often in the analysis of time series.
</p>
<p>
We are used to thinking of time series as somehow being
regularly spaced. For instance, we may be looking at preaggregated data,
like daily or weekly total sales, or measurements being made at
predefined points in time,
like closing prices of a stock or the number of companies in
business at the end of a given month.
</p>

</div>
</div> <div class="postbody">


<p>
In this context, we would attribute gaps in the data to some
procedural failure, defective sensors,
patients in a clinical trial not showing up, websites being down
etc.,
but often “missingness” is an intrinsic feature of the data
source at hand.
This is the case for many transaction based metrics:
</p>
<ul>
<li>
the price of a consumer good or a stock is only reported when a sale takes place,
</li>
<li>
the inventory of a warehouse is updated only when items are received or going out,
</li>
<li>
and, of course, the number of businesses only changes when companies start up or go out of business.
</li>
</ul>
<p>
Regardless of whether the reason is due to failure or or to plan, in many applications we have to somehow <strong>impute</strong>
the missing items for those times where no data is available.
</p>
<p>
Let’s have a look at some simulated data to see how this might work.
For concreteness we assume hourly time series of sales and prices of some products on a website or in a store.
</p>
<div class="sourceCode">
<pre class="sourceCode r"><code class="sourceCode r"><span class="kw">library</span>(tidyverse)
<span class="kw">library</span>(ggplot2)

<span class="co"># Parameters of the simulated data</span>

<span class="kw">set.seed</span>(<span class="dv">1756</span>)
NProd =<span class="st"> </span><span class="dv">20000</span> <span class="co"># number of articles </span>
NTime =<span class="st"> </span><span class="dv">100</span> <span class="co"># number of times , e.g. hours</span>
AvSales =<span class="st"> </span><span class="kw">sort</span>(<span class="kw">runif</span>(NProd, <span class="fl">0.7</span>, <span class="dv">5</span>)) <span class="co"># average hourly sales (lowest first)</span>
NPriceCh =<span class="st"> </span><span class="kw">sample</span>(<span class="dv">6</span>:<span class="dv">12</span>, NProd, <span class="dt">replace =</span> <span class="ot">TRUE</span>)<span class="co"># number of price changes </span>
StartPrice =<span class="st"> </span><span class="kw">runif</span>(NProd, <span class="dv">1</span>, <span class="dv">10</span>) <span class="co"># average price of each article</span>
PriceSteps &lt;-<span class="st"> </span><span class="kw">c</span>(-(<span class="dv">6</span>:<span class="dv">1</span>), <span class="dv">1</span>:<span class="dv">6</span>)*<span class="fl">0.05</span>

createData &lt;-<span class="st"> </span>function(art) {
## simulate prices and sales
stepPrice &lt;-<span class="st"> </span><span class="kw">rep</span>(<span class="dv">0</span>, NTime)
stepPrice[<span class="kw">sample</span>(<span class="kw">seq</span>(<span class="dv">1</span>, NTime, <span class="dt">by =</span> <span class="dv">3</span>), NPriceCh[art])] &lt;-
<span class="st">      </span><span class="kw">sample</span>(PriceSteps, NPriceCh[art], <span class="dt">replace =</span> <span class="ot">TRUE</span>)

<span class="kw">tibble</span>(
<span class="dt">sales =</span> <span class="kw">rpois</span>(NTime, AvSales[art]),
<span class="dt">article =</span> <span class="kw">paste</span>(<span class="st">"Prod"</span>, 1000000L +<span class="st"> </span>art),
<span class="dt">price =</span> <span class="kw">round</span>(StartPrice[art] *
<span class="st">                      </span><span class="kw">pmax</span>(<span class="fl">0.5</span>, <span class="dv">1</span> +<span class="st"> </span><span class="kw">cumsum</span>(stepPrice)), <span class="dv">2</span>),
<span class="dt">time =</span> <span class="dv">1</span>:NTime)
}

fulldat &lt;-<span class="st"> </span><span class="kw">bind_rows</span>(<span class="kw">lapply</span>(<span class="dv">1</span>:NProd, createData))

showdat &lt;-<span class="st"> </span><span class="kw">filter</span>(fulldat, article ==<span class="st">"Prod 1000001"</span>)
<span class="kw">head</span>(showdat)</code></pre>
</div>
<pre><code>## # A tibble: 6 × 4
##   sales      article price  time
##   &lt;int&gt;        &lt;chr&gt; &lt;dbl&gt; &lt;int&gt;
## 1     2 Prod 1000001  7.93     1
## 2     0 Prod 1000001  7.93     2
## 3     0 Prod 1000001  7.93     3
## 4     1 Prod 1000001  7.93     4
## 5     0 Prod 1000001  7.93     5
## 6     1 Prod 1000001  7.93     6</code></pre>
<p>
This is the full simulated data, including all 0 sales.
In a typical sales transaction system, all the red points in the graphs below would not appear.
</p>
<div class="sourceCode">
<pre class="sourceCode r"><code class="sourceCode r">gg1 &lt;-<span class="st"> </span><span class="kw">ggplot</span>(<span class="dt">data =</span> showdat,
<span class="kw">aes</span>(<span class="dt">x =</span> time, <span class="dt">y =</span> sales)) +<span class="st"> </span>
<span class="st">  </span><span class="kw">geom_step</span>(<span class="dt">color =</span> "grey" , <span class="dt">size =</span><span class="fl">1.5</span>) +<span class="st"> </span>
<span class="st">  </span><span class="kw">geom_point</span>(<span class="kw">aes</span>(<span class="dt">color =</span> (sales ==<span class="st"> </span><span class="dv">0</span>))) +
<span class="st">  </span><span class="kw">scale_color_manual</span>(<span class="dt">values =</span> <span class="kw">c</span>(<span class="st">"TRUE"</span> =<span class="st"> </span>"darkred", <span class="st">"FALSE"</span>=<span class="st"> </span><span class="ot">NA</span>),
<span class="dt">guide =</span><span class="ot">FALSE</span>)
gg1 </code></pre>
</div>
<br><div style="width: 99.99%; text-align: center;"><img src="http://www.quantitative-consulting.eu/graphics17/IMP_SimSales800X600.svg"></div>

<p>
Correspondingly, we would also be missing the displayed price
information for all time periods where no sale was performed.
</p>
<div class="sourceCode">
<pre class="sourceCode r"><code class="sourceCode r">gg2 &lt;-<span class="st"> </span><span class="kw">ggplot</span>(<span class="dt">data =</span> showdat,
<span class="kw">aes</span>(<span class="dt">x =</span> time, <span class="dt">y =</span> price)) +<span class="st"> </span>
<span class="st">  </span><span class="kw">geom_step</span>(<span class="dt">color =</span> "grey", <span class="dt">size =</span><span class="fl">1.5</span>) +<span class="st"> </span>
<span class="st">  </span><span class="kw">geom_point</span>(<span class="kw">aes</span>(<span class="dt">color =</span> (sales ==<span class="st"> </span><span class="dv">0</span>))) +
<span class="st">  </span><span class="kw">scale_color_manual</span>(<span class="dt">values =</span> <span class="kw">c</span>(<span class="st">"TRUE"</span> ="grey", <span class="st">"FALSE"</span>=<span class="st"> </span><span class="ot">NA</span>),
<span class="dt">guide =</span><span class="ot">FALSE</span>)
gg2</code></pre>
</div>
<br><div style="width: 99.99%; text-align: center;"><img src="http://www.quantitative-consulting.eu/graphics17/IMP_SimPrices800X600.svg"></div>

<p>
So, the simulated data set for our demonstration is obtained by removing the 0 sales:
</p>
<div class="sourceCode">
<pre class="sourceCode r"><code class="sourceCode r">dat &lt;-<span class="st"> </span>fulldat %&gt;%<span class="st"> </span><span class="kw">filter</span>(sales&gt;<span class="dv">0</span>)
<span class="kw">head</span>(dat)</code></pre>
</div>
<pre><code>## # A tibble: 6 × 4
##   sales      article price  time
##   &lt;int&gt;        &lt;chr&gt; &lt;dbl&gt; &lt;int&gt;
## 1     2 Prod 1000001  7.93     1
## 2     1 Prod 1000001  7.93     4
## 3     1 Prod 1000001  7.93     6
## 4     1 Prod 1000001  7.93     8
## 5     1 Prod 1000001  6.74    11
## 6     1 Prod 1000001  6.74    12</code></pre>
<p>
Given such a data set, what prices would we impute at times 2, 3, 5, 7, 9,  etc.? Since here we know the mechanism
leading to the missing data, a natural procedure would be to use the last valid price.
This is sometimes called “last observation carried forward”, or “locf” for short.
There is also “nocb” and many other methods whose relative merits,
drawbacks and biases you can learn a lot about by typing these keywords into Google.
</p>
<p>
All that I am going to say here: When running such a procedure,
you should have some notion about the mechanisms generating the data and
the reasons for missingness. For instance, if we are looking at retail
prices at a traditional store around the corner, assuming that the last
price from a few hours ago is still valid, seems reasonable enough. This
may have to be reconsidered if our data gap is at the beginning or the
end of a known promotional period, or for an online store, where prices
may be changed more dynamically, or if the gap spans a longer period of
time etc.
</p>
<p>
<em>Not</em> imputing your data, for example ignoring situations
where no sale took place in a business drivers or attribution analysis,
can be a serious mistake and can strongly bias the measurement of these
drivers.
</p>
<p>
This may be the topic of another article. For now, I want to look
at the technical implementation of the locf / nocb procedure, which is
at the basis of most other procedures. We start by sorting (assuming we
don’t know if the data is sorted) and add the information on the data
gaps
</p>
<div class="sourceCode">
<pre class="sourceCode r"><code class="sourceCode r"><span class="co"># arrange by hours and calculate lead and lag</span>
dat &lt;-<span class="st"> </span>dat %&gt;%<span class="st"> </span><span class="kw">ungroup</span>() %&gt;%
<span class="st">  </span><span class="kw">arrange</span>(article, time) %&gt;%
<span class="st">  </span><span class="kw">group_by</span>(article) %&gt;%
<span class="st">  </span><span class="kw">mutate</span>( <span class="dt">timeafter =</span> <span class="kw">lead</span>(time, <span class="dv">1</span>),
<span class="dt">timebefore =</span> <span class="kw">lag</span>(time, <span class="dv">1</span>),
<span class="dt">timeafter =</span> <span class="kw">ifelse</span>(<span class="kw">is.na</span>(timeafter), time +<span class="st"> </span><span class="dv">1</span>, timeafter),
<span class="dt">timebefore =</span> <span class="kw">ifelse</span>(<span class="kw">is.na</span>(timebefore), time -<span class="st"> </span><span class="dv">1</span>, timebefore) )
</code></pre>
</div>						<pre><code>## Time difference of 3.595551 secs</code></pre>
<div class="sourceCode">
<pre class="sourceCode r"><code class="sourceCode r"><span class="kw">head</span>(dat) </code></pre>
</div>						<pre><code>## Source: local data frame [6 x 6]
## Groups: article [1]
##
##   sales      article price  time timeafter timebefore
##   &lt;int&gt;        &lt;chr&gt; &lt;dbl&gt; &lt;int&gt;     &lt;dbl&gt;      &lt;dbl&gt;
## 1     2 Prod 1000001  7.93     1         4          0
## 2     1 Prod 1000001  7.93     4         6          1
## 3     1 Prod 1000001  7.93     6         8          4
## 4     1 Prod 1000001  7.93     8        11          6
## 5     1 Prod 1000001  6.74    11        12          8
## 6     1 Prod 1000001  6.74    12        17         11</code></pre>



<p>
We now create a template dataset
<code>
datImp
</code>
of what data should really be present. To create the expected
data, we are building the square of all articles with all times. For
simplicity, we decide not to deal with imputation before the first or
after the last observation. The variable “One” is only there to prevent
<code>
dplyr
</code>
from complaining that it does not find any common variables to join.
</p>
<div class="sourceCode">
<pre class="sourceCode r"><code class="sourceCode r"><span class="co"># max time and min time per article</span>
lims &lt;-<span class="st"> </span>dat %&gt;%<span class="st"> </span><span class="kw">group_by</span>(article) %&gt;%
<span class="st">                </span><span class="kw">summarise</span>( <span class="dt">mint =</span> <span class="kw">min</span>(time),
<span class="dt">maxt =</span> <span class="kw">max</span>(time),
<span class="dt">One =</span> 1L)

<span class="co"># expected sales  hours X articles</span>
datImp &lt;-<span class="st"> </span>lims %&gt;%
<span class="st">  </span><span class="kw">left_join</span>(<span class="kw">data_frame</span>(<span class="dt">time =</span> <span class="dv">1</span>:NTime,  <span class="dt">One =</span> 1L)) %&gt;%
<span class="st">  </span><span class="kw">filter</span>(time &gt;=<span class="st"> </span>mint, time &lt;=<span class="st"> </span>maxt) %&gt;%
<span class="st">  </span><span class="kw">select</span>(article, time)
</code></pre>
</div>
<pre><code>## Time difference of 0.7684343 secs</code></pre>
<div class="sourceCode">
<pre class="sourceCode r"><code class="sourceCode r"><span class="kw">head</span>(datImp) </code></pre>
</div>						<pre><code>## # A tibble: 6 × 2
##        article  time
##          &lt;chr&gt; &lt;int&gt;
## 1 Prod 1000001     1
## 2 Prod 1000001     2
## 3 Prod 1000001     3
## 4 Prod 1000001     4
## 5 Prod 1000001     5
## 6 Prod 1000001     6</code></pre>

<p>
You could now join the original data frame
<code>
dat
</code>
to the data frame of expected data and obtain the data set where missing data is marked as <code>
NA</code>.
This is the situation that most R-packages for imputation (e.g.
<code>
tidyr
</code>
,
<code>
zoo
</code>
,
<code>
padr
</code>
) take as a starting point.
<br>
In the present data set, where missingness is really absence of
data, I have found that the following lines, where
each " last observation " is just repeated as often aa is
required to fill the gap, work amazingly well also on large data sets.
</p>
<div class="sourceCode">
<pre class="sourceCode r"><code class="sourceCode r"><span class="co"># add next hour and last hour info</span>
datImp &lt;-<span class="st"> </span>datImp %&gt;%
<span class="st">  </span><span class="kw">mutate</span>(<span class="dt">lasttime =</span> <span class="kw">rep</span>(dat$time, dat$timeafter -<span class="st"> </span>dat$time),
<span class="dt">nexttime =</span> <span class="kw">rep</span>(dat$time, dat$time -<span class="st"> </span>dat$timebefore),
<span class="co"># lastart = rep(dat$art,dat$timeafter - dat$time),</span>
<span class="dt">lastprice =</span> <span class="kw">rep</span>(dat$price, dat$timeafter -<span class="st"> </span>dat$time),
<span class="dt">nextprice =</span> <span class="kw">rep</span>(dat$price, dat$time -<span class="st"> </span>dat$timebefore))
</code></pre>
</div>
<pre><code>## Time difference of 0.1430166 secs</code></pre>
<div class="sourceCode">
<pre class="sourceCode r"><code class="sourceCode r"><span class="kw">head</span>(datImp) </code></pre>
</div>						<pre><code>## # A tibble: 6 × 6
##        article  time lasttime nexttime lastprice nextprice
##          &lt;chr&gt; &lt;int&gt;    &lt;int&gt;    &lt;int&gt;     &lt;dbl&gt;     &lt;dbl&gt;
## 1 Prod 1000001     1        1        1      7.93      7.93
## 2 Prod 1000001     2        1        4      7.93      7.93
## 3 Prod 1000001     3        1        4      7.93      7.93
## 4 Prod 1000001     4        4        4      7.93      7.93
## 5 Prod 1000001     5        4        6      7.93      7.93
## 6 Prod 1000001     6        6        6      7.93      7.93</code></pre>
<p>
In my applications, this simple procedure has beaten all
implementations I have tried in SQL-dialects or with special purpose
packages.
Of course, before using this in any kind of production, one
should test thoroughly.
</p>
<div class="sourceCode">
<pre class="sourceCode r"><code class="sourceCode r">datComp &lt;-<span class="st"> </span>datImp %&gt;%<span class="st"> </span><span class="kw">left_join</span>(dat)

<span class="co"># must all be true etc. etc.</span>
<span class="kw">table</span>(datComp$lastprice ==<span class="st"> </span>datComp$price)
<span class="kw">table</span>(datComp$time &lt;=<span class="st"> </span>datComp$nexttime)
<span class="kw">table</span>(datComp$time &gt;=<span class="st"> </span>datComp$lasttime)</code></pre>
</div>
<p>
Since we started with the full simulated data in the first place, let’s wrap up this article with that comparison:

</p>
<div class="sourceCode">
<pre class="sourceCode r"><code class="sourceCode r">fulldat &lt;-<span class="st"> </span>fulldat %&gt;%<span class="st"> </span><span class="kw">left_join</span>(datImp)

showdat &lt;-<span class="st"> </span><span class="kw">filter</span>(fulldat, article ==<span class="st">"Prod 1000001"</span>)

gg3 &lt;-<span class="st"> </span><span class="kw">ggplot</span>(<span class="dt">data =</span> showdat,
<span class="kw">aes</span>(<span class="dt">x =</span> time, <span class="dt">y =</span> price)) +<span class="st"> </span>
<span class="st">  </span><span class="kw">geom_step</span>(<span class="dt">color =</span> "grey", <span class="dt">size =</span><span class="fl">1.5</span>) +<span class="st"> </span>
<span class="st">  </span><span class="kw">geom_step</span>(<span class="dt">data =</span> showdat, <span class="kw">aes</span>(<span class="dt">x =</span> time, <span class="dt">y =</span> lastprice),
<span class="dt">color =</span> "orange",
<span class="dt">size =</span><span class="fl">1.5</span>) +
<span class="st">  </span><span class="kw">geom_point</span>(<span class="kw">aes</span>(<span class="dt">color =</span> (sales ==<span class="st"> </span><span class="dv">0</span>))) +
<span class="st">  </span><span class="kw">scale_color_manual</span>(<span class="dt">values =</span> <span class="kw">c</span>(<span class="st">"TRUE"</span> ="darkred", <span class="st">"FALSE"</span>=<span class="st"> </span> "grey" ),
<span class="dt">guide =</span><span class="ot">FALSE</span>)
gg3 </code></pre>
</div>
<div style="width: 99.99%; text-align: center;"><img src="http://www.quantitative-consulting.eu/graphics17/IMP_ImputePrices800X600.svg"></div>
<br><p>
As you can see the technical procedure works nicely.  Unsurprisingly, differences occur
when prices were changed while no sale was made. So, in a real situation it will still be useful to add
external knowledge about the price setting to improve the quality of the imputation further.
</p>
</div>]]></description>
<pubDate>Fri, 21 Apr 2017 00:00:00 GMT</pubDate>
<author>bvaillant@quantitative-consulting.eu (Boris Vaillant)</author>
</item>
</channel>
</rss>
