<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Maarten Demeyer</title>
    <description>The latest articles on DEV Community by Maarten Demeyer (@mpjdem).</description>
    <link>https://dev.to/mpjdem</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F288593%2Fc91c59f8-1070-4c12-b510-6969ad23744b.jpeg</url>
      <title>DEV Community: Maarten Demeyer</title>
      <link>https://dev.to/mpjdem</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/mpjdem"/>
    <language>en</language>
    <item>
      <title>Game of Life, the DTerminal edition</title>
      <dc:creator>Maarten Demeyer</dc:creator>
      <pubDate>Tue, 07 Jan 2020 00:00:00 +0000</pubDate>
      <link>https://dev.to/mpjdem/game-of-life-the-dterminal-edition-4bld</link>
      <guid>https://dev.to/mpjdem/game-of-life-the-dterminal-edition-4bld</guid>
      <description>&lt;p&gt;Yet another offshoot from my &lt;a href="https://adventofcode.com/2019/"&gt;Advent of Code 2019&lt;/a&gt; adventures (&lt;a href="https://www.mpjdem.xyz/2019/12/11/advent-of-code-first-half.html"&gt;first half&lt;/a&gt;, &lt;a href="https://www.mpjdem.xyz/2019/12/31/advent-of-code-second-half.html"&gt;second half&lt;/a&gt;, &lt;a href="https://github.com/mpjdem/adventofcode2019"&gt;all solutions&lt;/a&gt;): on day 24, the challenge was to program a variant of &lt;a href="https://en.wikipedia.org/wiki/Conway%27s_Game_of_Life"&gt;Conway’s game of life&lt;/a&gt;, and I figured I might as well try my approach on the real thing!&lt;/p&gt;

&lt;p&gt;A quick google for existing implementations yields three main approaches: &lt;a href="http://johnramey.net/blog/2011/06/05/conways-game-of-life-in-r-with-ggplot2-and-animation/"&gt;nested for&lt;/a&gt;, &lt;a href="http://www.win-vector.com/blog/2018/10/conways-game-of-life-in-r-or-on-the-importance-of-vectorizing-your-r-code/"&gt;shifting of matrix rows and columns&lt;/a&gt;, and &lt;a href="https://github.com/dan-reznik/conway-game-of-life"&gt;repeated filtering of a coordinate data.frame&lt;/a&gt;. Visualisations tend to rely on R’s plotting capabilities, and more recently &lt;code&gt;{gganimate}&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;I used &lt;code&gt;data.table&lt;/code&gt; for the computations, because it’s fast and succinct. Here’s the setup of the Game of Life universe, randomly seeding half of the cells as alive, and defining the relevant relative ‘neighbourhood’ of each cell through a small auxiliary table. For those unfamiliar with &lt;code&gt;data.table&lt;/code&gt;, &lt;code&gt;CJ()&lt;/code&gt; performs a &lt;em&gt;cross-join&lt;/em&gt; to obtain all combinations of the vector arguments.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;library(data.table)

dims &amp;lt;- c(49, 49)
universe &amp;lt;- CJ(x = seq(dims[1]), y = seq(dims[2]), k = 1, cell = FALSE)
universe[, cell := sample(c(FALSE, TRUE), prod(dims), TRUE)]

neighbours &amp;lt;- CJ(xd = -1:1, yd = -1:1, k = 1)[xd != 0 | yd != 0]
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;Next, we want to define a function to perform one step (or &lt;strong&gt;tick&lt;/strong&gt; ) of the game. The basic approach is to do a full Cartesian join of the neighbourhood and the universe, to determine the neighbouring coordinates of each cell. We clip off at the edges (unlike a proper GoL universe, which is infinite), and aggregate grouped by the original cell coordinate to count the number of neighbours. &lt;code&gt;data.table&lt;/code&gt; allows us to express all of this in a really compact manner:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;gol_tick &amp;lt;- function(xy, sz, nb) {

  nb[xy, on = .(k), allow.cartesian = TRUE
    ][, nbx := x + xd][, nby := y + yd
    ][nbx &amp;gt;= 1 &amp;amp; nbx &amp;lt;= sz[1] &amp;amp; nby &amp;gt;= 1 &amp;amp; nby &amp;lt;= sz[2]
    ][xy, on = .(nbx = x, nby = y)
    ][, .(nnb = sum(i.cell)), by = .(x, y, cell, k)
    ][!cell &amp;amp; nnb == 3, cell := TRUE
    ][cell &amp;amp; (nnb &amp;lt; 2 | nnb &amp;gt; 3), cell := FALSE
    ][, nnb := NULL]

}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;So how about some visuals - and perhaps a bit of interaction? I chose to do this in the terminal, just to make the point that you can easily create these old-school games fully in R! You will need an ANSI-capable terminal emulator though, such as the default Ubuntu one. Do make it large enough (or the font small enough).&lt;/p&gt;

&lt;p&gt;First, the interaction part. To collect keypresses without pausing the universe to prompt the user, we need the &lt;a href="https://github.com/gaborcsardi/keypress"&gt;{keypress}&lt;/a&gt; package. Usage is as simple as calling &lt;code&gt;keypress(FALSE)&lt;/code&gt; to get the currently pressed key. Second, the visuals. Geometric unicode characters can provide a nice grid layout, but how do we ensure that we &lt;em&gt;update&lt;/em&gt; the visuals with each tick, instead of spitting out an endless sequence of universe states into the terminal? The answer is &lt;a href="https://en.wikipedia.org/wiki/ANSI_escape_code"&gt;ANSI escape codes&lt;/a&gt;, which allow you to colour the output, clear terminal lines, and crucially move the cursor back to a previous position. All of this is achieved simply by outputting strings starting with &lt;code&gt;\033[&lt;/code&gt; (or &lt;code&gt;\u001B[&lt;/code&gt;), followed by the ANSI instruction. For a more user-friendly interface to many of these functionalities have a look at the &lt;a href="https://github.com/r-lib/cli/"&gt;{cli}&lt;/a&gt; package - but here is the fully manual approach:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;library(keypress)

cat("\033[?25l")

repeat ({

  kp &amp;lt;- keypress(FALSE)

  universe[order(y, x)
    ][, cat(fifelse(.SD$cell, "\033[32;40m◼", "\033[90;40m◌"),
            "\033[K\n"),
      by = y]

  cat("\033[2K\033[33;40m", sum(universe$cell), "\n")

  if (kp == "q") break

  if (kp == "x") {
    new_cells &amp;lt;- sample(c(FALSE, TRUE), prod(dims), TRUE, c(9, 1))
    universe[, cell := cell | new_cells]
  }

  Sys.sleep(0.2)

  cat(paste0("\033[", dims[2] + 1, "A"))

  universe &amp;lt;- gol_tick(universe, dims, neighbours)

})

cat("\033[?25h")
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;The game speed is throttled using &lt;code&gt;Sys.sleep()&lt;/code&gt;, and the number of cells currently alive are displayed at the bottom. Two keys will be interpreted: &lt;code&gt;q&lt;/code&gt; exits the game, and &lt;code&gt;x&lt;/code&gt; insert new cells at random locations, to bring some new life to the eventually oscillatory universe!&lt;/p&gt;

&lt;p&gt;The full code can be found &lt;a href="https://gist.github.com/mpjdem/d2d1588ceb87408fd000830f22208741"&gt;in this gist&lt;/a&gt;. Run &lt;code&gt;Rscript game_of_life.R&lt;/code&gt; and you should be seeing something like this:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--NsYeiNqD--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://www.mpjdem.xyz/images/gol.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--NsYeiNqD--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://www.mpjdem.xyz/images/gol.png" alt=""&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Now go forth and multiply!&lt;/p&gt;

</description>
      <category>rstats</category>
      <category>r</category>
      <category>rdatatable</category>
    </item>
    <item>
      <title>Advent of Code, the second half</title>
      <dc:creator>Maarten Demeyer</dc:creator>
      <pubDate>Tue, 31 Dec 2019 00:00:00 +0000</pubDate>
      <link>https://dev.to/mpjdem/advent-of-code-the-second-half-5cnl</link>
      <guid>https://dev.to/mpjdem/advent-of-code-the-second-half-5cnl</guid>
      <description>&lt;p&gt;So &lt;a href="https://adventofcode.com/2019/"&gt;Advent of Code 2019&lt;/a&gt; ended last week, and I got all 50 stars. The challenges became considerably more challenging compared to &lt;a href="https://www.mpjdem.xyz/2019/12/11/advent-of-code-first-half.html"&gt;the first half&lt;/a&gt;, but base R did allow acceptably efficient solutions in almost all cases. My code is still on &lt;a href="https://github.com/mpjdem/adventofcode2019"&gt;GitHub&lt;/a&gt; - here’s what I learned about R by writing it! 🎄&lt;/p&gt;

&lt;h2&gt;
  
  
  Tail recursion grows the stack
&lt;/h2&gt;

&lt;p&gt;I kind of knew this already, but while R’s functional style invites using recursive functions, you will run into trouble if you recurse too deep. The simple reason is that each recursion will add to the call stack even when the recursion is the last expression of the function body (tail position). Many programming languages optimise for this situation to prevent stack growth, but R does not.&lt;/p&gt;

&lt;p&gt;In particular, naive recursive solutions to the maze puzzles of Day 18 and Day 20 often led me into the dreaded &lt;code&gt;Error: C stack usage XXXXXXX is too close to the limit&lt;/code&gt; message. There were hacky ways around this which allowed me to get the 🌟🌟 anyway, but the real solution I eventually found in &lt;a href="https://tailrecursion.com/wondr/posts/tail-recursion-in-r.html"&gt;this excellent blogpost by Alain Dipert&lt;/a&gt;. It’s called the &lt;strong&gt;trampoline&lt;/strong&gt; and it implements recursion as iteration. I cannot possibly do a better job than Alain explaining it, so go and read his article!&lt;/p&gt;

&lt;p&gt;Related to this, using deep recursion on several of the Advent of Code days made it apparent that creating unnecessary temporary variables in the function body will grow the size of each execution environment, and thereby the total memory usage of R.&lt;/p&gt;

&lt;p&gt;Consider:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;countdown &amp;lt;- function(n) {
    if (n &amp;gt; 0) {
        tmp &amp;lt;- runif(10000)
        countdown(n - 1)
    } else {
        gc()
    }
}

countdown(100)

## used (Mb) gc trigger (Mb) max used (Mb)
## Ncells 543979 29.1 1233580 65.9 641291 34.3
## Vcells 2017084 15.4 8388608 64.0 2536825 19.4

countdown(1000)

## used (Mb) gc trigger (Mb) max used (Mb)
## Ncells 550718 29.5 1233580 65.9 641291 34.3
## Vcells 11018937 84.1 15315970 116.9 11103124 84.8
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;Comment out the &lt;code&gt;tmp&lt;/code&gt; assignment to see that it is indeed &lt;code&gt;tmp&lt;/code&gt; which causes the difference.&lt;/p&gt;

&lt;p&gt;So why use recursion at all in R, if it requires all these extra steps and considerations? For me, it is simply a better fit to the way my brain works when parsing a problem, and I am less prone to making mistakes as compared to using while/for flow control with constantly updated variables. As a bonus, recursive functions are also easier to unit test!&lt;/p&gt;

&lt;h2&gt;
  
  
  &amp;lt;&amp;lt;- can be very convenient
&lt;/h2&gt;

&lt;p&gt;In my professional coding life I have rarely used the &lt;code&gt;&amp;lt;&amp;lt;-&lt;/code&gt; operator, which allows you to assign a variable in the &lt;em&gt;enclosing environment&lt;/em&gt; of a function. Because of R’s &lt;a href="https://adv-r.hadley.nz/functions.html#lexical-scoping"&gt;lexical scoping&lt;/a&gt;, this is always the environment in which the function was defined, not the one in which it was called. But unfortunately &lt;code&gt;&amp;lt;&amp;lt;-&lt;/code&gt; causes functions to have side-effects, making code using &lt;code&gt;&amp;lt;&amp;lt;-&lt;/code&gt; hard to read and to debug.&lt;/p&gt;

&lt;p&gt;Yet in Advent of Code, I used it liberally. Often as a timesaver, so I didn’t have to pass variables around as function arguments. But on Day 14, it became also a lifesaver for keeping a common state between recursive function calls.&lt;/p&gt;

&lt;p&gt;Consider this example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;countdown_with_offshoot &amp;lt;- function(n) {
    if (n &amp;gt; 0) {
        if (sum(vals) &amp;gt; 100) {
            vals &amp;lt;&amp;lt;- sample(vals, floor(length(vals) / 2))
            countdown_with_offshoot(sum(vals &amp;gt; 1))
        } else {
            vals &amp;lt;&amp;lt;- c(vals, sample(10, 1))
        }
        countdown_with_offshoot(n - 1)
    }
}

vals &amp;lt;- numeric(0)
countdown_with_offshoot(100)
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;This will sometimes launch an additional countdown based on numbers generated inside the recursive function calls. Because of lexical scoping, the enclosing environment is the same no matter how deep the recursions run, and &lt;code&gt;&amp;lt;&amp;lt;-&lt;/code&gt; will therefore always assign to the same variable.&lt;/p&gt;

&lt;p&gt;Can this be solved without &lt;code&gt;&amp;lt;&amp;lt;-&lt;/code&gt;? Of course. But you will need to both pass &lt;code&gt;vals&lt;/code&gt; along with the countdown itself, and return it when the offshoot countdown ends. And every function execution environment will keep its own state of &lt;code&gt;vals&lt;/code&gt; in memory. &lt;code&gt;&amp;lt;&amp;lt;-&lt;/code&gt; simplifies the code greatly and reduces memory use. For a one-off coding puzzle, that is a more than acceptable trade-off!&lt;/p&gt;

&lt;h2&gt;
  
  
  R does not support large integers
&lt;/h2&gt;

&lt;p&gt;Day 22 was a mathematical puzzle requiring &lt;a href="https://en.wikipedia.org/wiki/Modular_exponentiation"&gt;modular exponentiation&lt;/a&gt; of large integers. To my surprise, I was unable to solve it in base R by implementing modular exponentiation myself, because there is no support for very large integers! The &lt;code&gt;integer&lt;/code&gt; type is 32-bit, and the &lt;code&gt;double&lt;/code&gt; type has imperfect precision above &lt;code&gt;2**53&lt;/code&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;## Explicitly casting to integer will yield NA
as.integer(2**53)

## Warning: NAs introduced by coercion to integer range

## [1] NA

## Below 2**53 a double represents integers accurately
(2**52 + 1:10) %% 2

## [1] 1 0 1 0 1 0 1 0 1 0

## Above 2**53 computations become innaccurate
## There is no warning for this behaviour
(2**53 + 1:10) %% 2

## [1] 0 0 0 0 0 0 0 0 0 0
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;I had to resort to the &lt;code&gt;{gmp}&lt;/code&gt; package here, a wrapper around the &lt;a href="https://gmplib.org/"&gt;GNU Multiple Precision Arithmetic Library&lt;/a&gt; library which does allow accurate computations with large integers. To install on Debian derivatives, run &lt;code&gt;sudo apt-get install libgmp-dev&lt;/code&gt; prior to installing the R package.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;(gmp::as.bigz(2**53) + 1:10) %% 2

## Big Integer ('bigz') object of length 10:
## [1] 1 0 1 0 1 0 1 0 1 0
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;Fortunately, &lt;code&gt;{gmp}&lt;/code&gt; also has modular exponentiation built in, as &lt;code&gt;gmp::powm()&lt;/code&gt;, so I could skip the manual implementation altogether!&lt;/p&gt;

&lt;h2&gt;
  
  
  More for the wishlist
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://www.mpjdem.xyz/2019/12/11/advent-of-code-first-half.html"&gt;Last time&lt;/a&gt; I complained about R not allowing key-value lookups using keys of any type, like Python’s dictionaries do allow (well, for immutable types). I ran into this problem multiple times again, although in the case of &lt;code&gt;(x,y)&lt;/code&gt; coordinates I sometimes used complex numbers instead in a single data frame column, on which I could then filter to retrieve the associated values. But that is a rather limited use case.&lt;/p&gt;

&lt;p&gt;Given that most of the Advent of Code challenges were general computing and not data science puzzles, R’s limitations in this regard were exposed as the problems became more complex. One-based indexing was sometimes slightly annoying when relying on modulus operations to access a vector, but this is unlikely to ever change in R. Immediate unpacking of multiple return values, however, would be a nice feature. The &lt;code&gt;{zeallot}&lt;/code&gt; package implements this but it would great to see it in base R, so we don’t always need to construct and pick apart &lt;code&gt;list&lt;/code&gt; objects.&lt;/p&gt;

&lt;p&gt;For instance, from the documentation of &lt;code&gt;{zeallot}&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;library(zeallot)

c(lat, lon) %&amp;lt;-% list(38.061944, -122.643889)
print(lat)

## [1] 38.06194
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;Likewise I was often bothered by how heavy-handed it feels to define a class in R, or at least some other type of structural template for pieces of non-tabular data which belong together. When using R for data science this is rarely a problem, for general computing some syntactic elegance would be welcomed - perhaps something similar to &lt;a href="https://clojuredocs.org/clojure.core/defrecord"&gt;defrecord&lt;/a&gt; in Clojure. In practice I usually just relied on a loosely defined &lt;code&gt;list&lt;/code&gt; instead, but this becomes hard to manage for complex code.&lt;/p&gt;

&lt;h2&gt;
  
  
  Oh, and give me graphs
&lt;/h2&gt;

&lt;p&gt;Around 11 out of 14 minutes of the total running time for all 25 days of my Advent of Code solutions are spent on Day 18 and Day 20, both maze pathfinding puzzles. They were solved through a combination of random walks where visited paths are tagged as such, and recursive functions. Other people, using other languages, appear to have relied on graphs a lot, where the shortest path in a maze is the shortest path across the nodes of a graph.&lt;/p&gt;

&lt;p&gt;I could have tried to implement the main algorithms used like Dijkstra and BFS in base R, but I suspected that it would be too inefficient, without access to &lt;code&gt;{Rcpp}&lt;/code&gt;. For implementing such algorithms natively a language like Julia would shine - not R. Now that Advent of Code is over and my self-imposed restriction to base is over though, I’d love to try and see how well &lt;code&gt;{igraph}&lt;/code&gt; would perform in R on these particular challenges!&lt;/p&gt;

&lt;p&gt;But that’ll be something for the new decade. HNY! 🎆&lt;/p&gt;

</description>
      <category>rstats</category>
      <category>r</category>
      <category>adventofcode</category>
    </item>
    <item>
      <title>Advent of Code, the first half</title>
      <dc:creator>Maarten Demeyer</dc:creator>
      <pubDate>Wed, 11 Dec 2019 00:00:00 +0000</pubDate>
      <link>https://dev.to/mpjdem/advent-of-code-the-first-half-2hng</link>
      <guid>https://dev.to/mpjdem/advent-of-code-the-first-half-2hng</guid>
      <description>&lt;p&gt;&lt;strong&gt;’tis the season to be coding!&lt;/strong&gt; As I’m sure you’ve all noticed (cough) I have been rather quiet on the blogging front lately because my leisure coding time has been consumed by the annual &lt;a href="https://adventofcode.com/2019/"&gt;Advent of Code&lt;/a&gt; challenge. It would have been fun to use this to become more proficient in Clojure, but I don’t have &lt;em&gt;that&lt;/em&gt; much leisure coding time, so base R it is. The main goal, other than plain old fun, is to give myself a good refresh of what base can do.&lt;/p&gt;

&lt;p&gt;All solutions can be found on my &lt;a href="https://github.com/mpjdem/adventofcode2019/"&gt;Github&lt;/a&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  Base is rich and versatile
&lt;/h2&gt;

&lt;p&gt;I’ve been surprised to remember how much I actually like base R, given how avid a user I’ve been of &lt;code&gt;data.table&lt;/code&gt;, &lt;code&gt;purrr&lt;/code&gt; and &lt;code&gt;rlang&lt;/code&gt; in recent years. The &lt;code&gt;apply&lt;/code&gt; family, array operations and functional programming tools like &lt;code&gt;Reduce()&lt;/code&gt; will get you very far indeed on moderately sized data. When using data frames base R falls well short in terms of API, compared to the modern champions of data munging, but it does still do the job.&lt;/p&gt;

&lt;p&gt;Inevitably I’ve learned a few new things about base R. Here are some of the highlights.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;rle()&lt;/code&gt; was brought to my attention by the &lt;a href="https://github.com/adam-gruer/aoc2019/blob/master/04.R"&gt;Day 4 solution of Adam Gruer&lt;/a&gt;. This was easily my worst day of Advent Of Code in terms of succinctness and speed of the solution, and it would have helped a lot to know that Run Length Encoding of repeated values in a vector is available in base R, just like that.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;rle(c("a","a","b"))
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;





&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;## Run Length Encoding
## lengths: int [1:2] 2 1
## values : chr [1:2] "a" "b"
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;&lt;code&gt;strsplit()&lt;/code&gt; was not a new function to me, but I didn’t know it can take &lt;code&gt;split = ""&lt;/code&gt; as an argument to just split out every individual character! Very helpful when many puzzle inputs are given as plain text character sequences.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;strsplit("abcde", split = "")
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;





&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;## [[1]]
## [1] "a" "b" "c" "d" "e"
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;&lt;code&gt;which()&lt;/code&gt; is another basic function that I’ve used so often before, without realising it can compute n-D array indices through the &lt;code&gt;arr.ind = TRUE&lt;/code&gt; argument.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;mat &amp;lt;- matrix(sample(c(FALSE, TRUE), size = 16, replace = TRUE), ncol = 4)
which(mat, arr.ind = TRUE)
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;





&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;## row col
## [1,] 1 1
## [2,] 3 1
## [3,] 2 2
## [4,] 2 3
## [5,] 3 3
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;&lt;code&gt;merge()&lt;/code&gt; is the natural replacement of &lt;code&gt;dplyr&lt;/code&gt;’s join functions in base R, but did you know it can also do a full crossing of a data frame with itself? Just set the &lt;code&gt;by&lt;/code&gt; argument explicitly to empty.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;df &amp;lt;- data.frame(a = letters[1:3], b = 1:3)
merge(df, df, by = character(0), suffixes = c("_one", "_two"))
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;





&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;## a_one b_one a_two b_two
## 1 a 1 a 1
## 2 b 2 a 1
## 3 c 3 a 1
## 4 a 1 b 2
## 5 b 2 b 2
## 6 c 3 b 2
## 7 a 1 c 3
## 8 b 2 c 3
## 9 c 3 c 3
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;Not all is great, however. Today (&lt;a href="//https//github.com/mpjdem/aoc19/blob/master/aoc19_day11.R"&gt;Day 11&lt;/a&gt;) I really missed being able to key named lists or envs by something else than strings. In Python dicts you can use any immutable type, including tuples. So I could have directly used &lt;code&gt;(x,y)&lt;/code&gt; coordinates as a key, instead of having to awkwardly paste and parse them to and from strings (or take a cumbersome detour via data frame indexing). A longstanding shortcoming for R as a general-purpose computing language, in my opinion.&lt;/p&gt;

&lt;h2&gt;
  
  
  …not another intcode!
&lt;/h2&gt;

&lt;p&gt;I’ve been particularly fond of the ‘intcode’ challenges. With ‘fond of’, I mean I hated them. But in a good way. Not to be too cryptic to non-participants, these are challenges where a sequence of integers is to be processed as if they were read/write/jump/print/… instructions within the sequence, each followed by a variable number of parameters. With every new challenge, more instructions and possible interpretations of the integers are added.&lt;/p&gt;

&lt;p&gt;This means these intcode challenges are really challenges about software design and development, where scope is ever creeping and requirements are ever changing. I like this. It forces you to strike a balance between being pragmatic about the challenge of the day, and still making the solution extensible on future days. This to me is far more relevant and realistic as a coding challenge, and far more telling of actual skill and craft as a developer, than coming up with a clever algorithmic one-liner.&lt;/p&gt;

&lt;h2&gt;
  
  
  A favourite
&lt;/h2&gt;

&lt;p&gt;If I could pick a favourite so far, it would have to be &lt;a href="https://adventofcode.com/2019/day/6"&gt;Day 6: Universal Orbit Map&lt;/a&gt;. A list of objects is given such that each object orbits exactly one other object. The challenge is to compute how many orbits there are in total, both direct and indirect. Many people were immediately triggered into thinking ‘graph!’, and in truth, so was I. But being restricted to base R, I looked for a less exhausting solution. So I quickly realised that there was really no need for a full graph, we only need to separately trace back each individual object to the common center of gravity and add up all the steps.&lt;/p&gt;

&lt;p&gt;Here is the full solution, using &lt;a href="https://www.mpjdem.xyz/blog/aoc_input6.txt"&gt;this input&lt;/a&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;inp &amp;lt;- read.delim("aoc_input6.txt", sep = ")", header = FALSE,
                  col.names = c("orbitee", "orbiter"),
                  stringsAsFactors = FALSE)

memo_env &amp;lt;- new.env()

count_orbits &amp;lt;- function(obj) {
  if (!is.null(memo_env[[obj]])) {
    memo_env[[obj]]
  } else if (obj %in% inp$orbiter) {
    memo_env[[obj]] &amp;lt;- 1 + count_orbits(inp[inp$orbiter == obj,]$orbitee)
  } else {
    0
  }
}

sum(sapply(unique(inp$orbiter), count_orbits))
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;





&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;## [1] 142915
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;I enjoyed this because there is so much really powerful stuff going on in so few lines of code. First we read the data just like a two-column CSV, but using &lt;code&gt;)&lt;/code&gt; as the delimiter. The &lt;strong&gt;data frame&lt;/strong&gt; structure comes very naturally to R, and often offers an intuitive insight into a problem. This goes in general for many of the Advent of Code challenges - when using a data frame you always have the current state of the data clearly visible in front of you, and can work incrementally towards a solution using all of R’s great data frame manipulation tools. In this case the data frame is mainly useful as an explicit lookup table.&lt;/p&gt;

&lt;p&gt;Then there is &lt;strong&gt;recursion&lt;/strong&gt; going on - the &lt;code&gt;count_orbits()&lt;/code&gt; function calls itself to find the next orbited object, until it reaches the center. Every recursion adds 1 to the counter. Because many of these paths are partially shared, the recursive function can be sped up considerably by using &lt;strong&gt;memoisation&lt;/strong&gt; - we really don’t need to retrace a path we’ve been down already. Instead, we save the solution in a dedicated environment (a named list or vector would work as well, but environments scale better for larger problems) and retrieve it as needed.&lt;/p&gt;

&lt;p&gt;Finally, the &lt;strong&gt;sapply&lt;/strong&gt; call shows that you don’t need for-loops much, even in base R, if you can condense repeated independent operations on vector elements into a unary function. The resulting vector is immediately aggregated into the puzzle solution on the same line. A recipe that is succinct and clear, and oh so widely applicable. However much I love &lt;code&gt;purrr&lt;/code&gt; for its explicit consistency, 90%+ of its practical use cases are really already covered in base R - it’s easy to forget when you’re hooked on the &lt;code&gt;%&amp;gt;%&lt;/code&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  All right then
&lt;/h2&gt;

&lt;p&gt;Back into Santa’s service I go!&lt;/p&gt;

</description>
      <category>rstats</category>
      <category>r</category>
      <category>adventofcode</category>
    </item>
    <item>
      <title>R scripts as command line tools</title>
      <dc:creator>Maarten Demeyer</dc:creator>
      <pubDate>Wed, 13 Nov 2019 00:00:00 +0000</pubDate>
      <link>https://dev.to/mpjdem/r-scripts-as-command-line-tools-2k6c</link>
      <guid>https://dev.to/mpjdem/r-scripts-as-command-line-tools-2k6c</guid>
      <description>&lt;p&gt;Most R users rely heavily on the interactive console for writing and executing code, but sometimes you will want to expose your work to a world outside of that cosy cocoon. One solution is to wrap a web API around your code, for instance using the excellent &lt;a href="https://github.com/rstudio/plumber"&gt;{plumber}&lt;/a&gt;. The other main option is to wrap it in a &lt;strong&gt;command-line interface (CLI)&lt;/strong&gt;, so it can be used from the shell like any regular program.&lt;/p&gt;

&lt;p&gt;To run R code directly from a Linux shell, we must use the &lt;code&gt;Rscript&lt;/code&gt; executable instead of regular &lt;code&gt;R&lt;/code&gt; (or alternatively, &lt;a href="https://cran.r-project.org/web/packages/littler/index.html"&gt;{littler}&lt;/a&gt;). For instance, suppose we want to expose the functionality of the &lt;a href="https://github.com/hadley/emo"&gt;{emo}&lt;/a&gt; package - retrieve an emoji by name.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# To install {emo}, do: remotes::install_github("hadley/emo")
# commandArgs() parses arguments provided on the command line into a &amp;lt;list&amp;gt;
args &amp;lt;- commandArgs(trailingOnly = TRUE)

# Use cat() for output
cat(emo::ji(args[[1]]), "\n")
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;Save this code to &lt;code&gt;getemo.R&lt;/code&gt;, and then this is what &lt;code&gt;Rscript&lt;/code&gt; enables us to do:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Rscript getemo.R unicorn
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;&lt;em&gt;(the character encoding and font used by your terminal must support rendering unicode emojis)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;So far so good, and in many cases this will even be good enough! But our little script does not yet behave like a regular command-line tool, where we would hope to just be able to do &lt;em&gt;from any directory&lt;/em&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;getemo unicorn
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;h1&gt;
  
  
  So how?
&lt;/h1&gt;

&lt;p&gt;First let me give a hat tip to &lt;a href="https://dev.to/colinfay/create-a-cli-for-r-with-npm-3o43"&gt;Colin Fay for describing a method&lt;/a&gt; where you let the Node package manager, &lt;code&gt;npm&lt;/code&gt;, do all the work. This is really great when you are already a Node user, but if you’re not it is probably too much overhead simply to expose an R script.&lt;/p&gt;

&lt;p&gt;Three simple steps are all we really need.&lt;/p&gt;

&lt;h2&gt;
  
  
  1. Add a shebang line at the top
&lt;/h2&gt;

&lt;p&gt;Linux systems (and other Unix-likes) have a standard way of specifying in a comment at the top of plain-text scripts which program should be used to run them - the &lt;em&gt;shebang&lt;/em&gt;. You could use:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;#!/usr/bin/Rscript --vanilla
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;The &lt;code&gt;--vanilla&lt;/code&gt; argument makes sure that user-specific R settings are ignored, and that there is no saving or restoring of workspaces. This makes the script more portable to other systems.&lt;/p&gt;

&lt;p&gt;You will often see &lt;code&gt;/usr/bin/env Rscript&lt;/code&gt; used, also for reasons of portability. But there are some potential version differences if you want to specify the &lt;code&gt;--vanilla&lt;/code&gt; argument, so if you’re unsure just stick to the direct version for now.&lt;/p&gt;

&lt;h2&gt;
  
  
  2. Make the script executable
&lt;/h2&gt;

&lt;p&gt;Before you can run a script directly from the command line, you must tell the file system that this plain text file is indeed a script which can be run, rather than any old text file, and that this user is allowed to run it. So do:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;chmod +x getemo.R
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;You will be able to check with a simple &lt;code&gt;ls -all getemo.R&lt;/code&gt; command that it has received x’s in its permissions. It can now be run with:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;./getemo.R unicorn
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;We’re getting there, but we still needed to specify the path to the script explicitly to be able to run it (in this case, the local directory &lt;code&gt;.&lt;/code&gt;).&lt;/p&gt;

&lt;h2&gt;
  
  
  3. Make it available in your $PATH
&lt;/h2&gt;

&lt;p&gt;Now for the &lt;em&gt;‘from any directory’&lt;/em&gt; part of the requirements. Running a program from any directory is typically achieved by adding the directory of that program to the &lt;code&gt;$PATH&lt;/code&gt; environment variable. But we don’t want to be littering this with custom script directories so let’s see what is already in &lt;code&gt;$PATH&lt;/code&gt;, using &lt;code&gt;echo $PATH&lt;/code&gt;. Either &lt;code&gt;~/bin&lt;/code&gt; or &lt;code&gt;~/.local/bin&lt;/code&gt;, or both, are often present in desktop linux installations; these are standard directories for executables belonging to your home directory. If you &lt;code&gt;ls -all&lt;/code&gt; them you will notice they mainly contain &lt;a href="https://www.gnu.org/software/coreutils/manual/html_node/ln-invocation.html"&gt;symbolic links&lt;/a&gt; to files in other directories.&lt;/p&gt;

&lt;p&gt;This is exactly what we are going to do with our R script as well. In addition, let’s drop the &lt;code&gt;.R&lt;/code&gt; extension when making that &lt;code&gt;-s&lt;/code&gt; link. So, assuming that &lt;code&gt;~/bin/&lt;/code&gt; is in our &lt;code&gt;$PATH&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;ln -s -r getemo.R ~/bin/getemo
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;The &lt;code&gt;-r&lt;/code&gt; option makes the link between the paths relative, since I don’t know in which directory the original script would be placed on your computer. You can omit it but then you should specify both paths in full.&lt;/p&gt;

&lt;p&gt;Now we can get the desired result by executing, from any directory:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;getemo unicorn
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;The full script, including the shebang, can be found in &lt;a href="https://gist.github.com/mpjdem/00f45e49e4ac894ca3dcc6c6a9c92753"&gt;this gist&lt;/a&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  Do more
&lt;/h2&gt;

&lt;p&gt;We didn’t make the CLI tool available to the entire system here, only to your user profile. Unless you have good reasons to the contrary, I would advise to keep it that way. Many Linux desktops have in practice only one user, and inside Docker containers you can use the &lt;code&gt;/root&lt;/code&gt; user. If you do want to expose a script system-wide, &lt;code&gt;/usr/local/bin&lt;/code&gt; is usually the appropriate directory.&lt;/p&gt;

&lt;p&gt;To learn how to write better CLI tools in R, have a look at &lt;a href="https://blog.sellorm.com/2017/12/18/learn-to-write-command-line-utilities-in-r/"&gt;Mark Sellor’s blog&lt;/a&gt; on the topic. For parsing and documenting CLI arguments, I personally prefer &lt;a href="https://github.com/trevorld/r-argparse"&gt;{argparse}&lt;/a&gt; if the Python dependency is not an issue; and &lt;a href="https://github.com/docopt/docopt.R"&gt;{docopt}&lt;/a&gt; when it is. For stylising the visual outputs, &lt;a href="https://github.com/r-lib/cli"&gt;{cli}&lt;/a&gt; is great.&lt;/p&gt;

&lt;h1&gt;
  
  
  Cool, but why?
&lt;/h1&gt;

&lt;p&gt;Well here’s a question people should ask more often! Some of the reasons I can see are:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Make your work available to non-R users in an interface they can understand&lt;/li&gt;
&lt;li&gt;Make your work available to production frameworks that run tasks as commands, like &lt;a href="https://airflow.apache.org/"&gt;Airflow&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;For your own convenience, expose R-specific functionality to the command line. &lt;code&gt;emo::ji()&lt;/code&gt; was arguably not the world’s greatest example of a productivity improvement, but what about wrapping something like &lt;a href="https://github.com/ropensci/skimr"&gt;{skimr}&lt;/a&gt;, to beautifully preview CSVs?&lt;/li&gt;
&lt;li&gt;R might not always be the objectively best tool for the job but it could well be &lt;em&gt;your&lt;/em&gt; best tool. If R is indeed the language you are most fluent in, it will probably be most productive for you to script even non-data-related tasks in R.&lt;/li&gt;
&lt;li&gt;If written properly, an R command line tool can be used together with other, non-R command line tools. For instance to provide data to it, or to further process the output. But that’s a topic for another time!&lt;/li&gt;
&lt;/ul&gt;

&lt;h1&gt;
  
  
  Cool.
&lt;/h1&gt;

&lt;p&gt;I know!&lt;/p&gt;

</description>
      <category>rstats</category>
      <category>r</category>
      <category>cli</category>
    </item>
  </channel>
</rss>
