<p><div><div><div><div data-show-faces="false" data-height="21" data-width="100" data-layout="button_count" data-send="true" data-href="https://www.r-bloggers.com/dplyr-mclapply-for-loop-and-speed/"></div></div><div></div></div><div></div></div>
<div>
(This article was first published on <strong><a href="https://scottishsnow.wordpress.com/2018/02/18/dplyr-lapply-for-loop/"> R – scottishsnow</a></strong>, and kindly contributed to <a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers)</a> </div>
<p>I was at <a rel="nofollow" href="https://twitter.com/edinb_r" target="_blank">EdinbR</a> on Friday evening and <a rel="nofollow" href="https://twitter.com/drob" target="_blank">David Robinson</a>‘s talk prompted some excellent discussions, not least with <a rel="nofollow" href="https://twitter.com/TeamShrub" target="_blank">Isla</a> and <a rel="nofollow" href="https://twitter.com/gndaskalova" target="_blank">Gergana</a>. One topic was on dplyr and lapply. I started using R in 2012, just before dplyr came to prominence and so I seem to have one foot in base and the other in the tidyverse. Ambitiously aiming for the best of both worlds!</p>
<p>I often use lapply to wrap up my scripts which clean and process files, but Isla pointed out I could do this with dplyr. I can’t figure out (with available Sunday time) how to use write_csv in a pipe and pass it an argument for a file name (please tell me in the comments!), <em>without</em> resorting to making a loop/*apply.</p>
<p>This post is for all those folk who might be considering wrapping some tidyverse commands in a function to make their code cleaner and hopefully gain some speed advantages.</p>
<p>For this example I’ve created a dummy set of raw data that we can make some arbitrary selection and transformation on and save as clean. In this case I’ve created dates with some observations happening each day, labelled as ‘a’ to ‘c’. Alongside this I’ve duplicated these columns to give us something to drop. Dummy data created with:</p>
<pre>
library(tidyverse)

# Dummy files to process
dir.create(&quot;./temp/raw&quot;, recursive=T)
dir.create(&quot;./temp/clean&quot;)

lapply(1950:2017, function(i){
   date = seq.Date(as.Date(paste0(i, &quot;-01-01&quot;)),
                 as.Date(paste0(i, &quot;-12-31&quot;)),
                 by=1)
   a = rnorm(length(date))
   a1 = rnorm(length(date))
   a2 = rnorm(length(date))
   b = rpois(length(date), 10)
   b1 = rpois(length(date), 10)
   b2 = rpois(length(date), 10)
   c = rexp(length(date), 5)
   c1 = rexp(length(date), 5)
   c2 = rexp(length(date), 5)

   write_csv(data.frame(date, a, b, c),
             paste0(&quot;./temp/raw/file_&quot;, i, &quot;.csv&quot;))
})
</pre>
<p>We’ve now got a directory with 68 csv files, each containing some fabricated daily data. In order to read files into R, the first thing to do is get a path to it, we can do this with `list.files()`:</p>
<pre>
# Get a vector of file names
f = list.files(&quot;./temp/raw&quot;, pattern=&quot;file&quot;)
</pre>
<p>Now we have an object, `f`, which contains all our file names we can write a process to get them ready for analysis. I’m illustrating this by selecting 4 columns (date, a, b and c) and converting them to a long <a rel="nofollow" href="http://vita.had.co.nz/papers/tidy-data.pdf" target="_blank">tidy format</a>. I’ve had a stab at writing this process in tidyverse alone, but can’t figure out how to pass `write_csv()` a file name. I suspect the answer lies in turning `f` into a data frame with a column for in and a column for out. Seems pretty awkward to me. I welcome answers in the comments!</p>
<pre>
# Interactive dplyr
# Who knows what ??? should take, I don't!
system.time(
paste0(&quot;./temp/raw/&quot;, f) %>%
   read_csv() %>%
   select(date, a, b, c) %>%
   gather(variable, value, -date) %>%
   write_csv(???)
)
</pre>
<p>The above doesn’t work, but we can adapt it slightly to make it a function. We’re now able to pass our tidyverse code individual file names, here represented by `i`. Finally, the clean data are written out into the clean folder. In the real world we may also want to change the file name to reflect the clean status.</p>
<pre>
# As a function
read_clean_write = function(i){
   paste0(&quot;./temp/raw/&quot;, i) %>%
      read_csv() %>%
      select(date, a, b, c) %>%
      gather(variable, value, -date) %>%
      write_csv(paste0(&quot;./temp/clean/&quot;, i))
}
</pre>
<p>Finally, we can run the above as a loop (usually bad), lapply or something else:</p>
<pre>
# Loop
for (j in f){
   read_clean_write(j)
}

# lapply
lapply(f, read_clean_write)
</pre>
<p>But how fast were they? Can we get faster? Thankfully R provides `system.time()` for timing code execution. In order to get faster, it makes sense to use all the processing power our machines have. The ‘parallel’ library has some great tools to help us run our jobs in parallel and take advantage of multicore processing. My favourite is `mclapply()`, because it is very very easy to take an `lapply` and make it multicore. Note that mclapply doesn’t work on Windows. The following script runs the `read_clean_write()` function in a for loop (boo, hiss), lapply and mclapply. I’ve run these as list elements to make life easier later on.</p>
<pre>
library(parallel)

# Loop
times = list(
   loop = system.time(
      for (j in f){
         read_clean_write(j)
      }
   ),
   lapply = system.time(
      lapply(f, read_clean_write)
   ),
   mclapply = system.time(
      mclapply(f, mc.cores=4, read_clean_write)
   )
)
</pre>
<p>Next we can plot up these results. I’m using sapply to get only the elapsed time from the proc.time object, and then cleaning the elapsed part from the vector name.</p>
<div data-shortcode="caption" class="wp-caption"><img data-orig-file="https://scottishsnow.files.wordpress.com/2018/02/barplot.png?w=456" data-orig-size="1000,500" data-medium-file="https://scottishsnow.files.wordpress.com/2018/02/barplot.png?w=456?w=300" data-attachment-id="1554" data-image-meta="{" data-image-description="" src="https://scottishsnow.files.wordpress.com/2018/02/barplot.png?w=456" data-permalink="https://scottishsnow.wordpress.com/2018/02/18/dplyr-lapply-for-loop/barplot/" data-large-file="https://scottishsnow.files.wordpress.com/2018/02/barplot.png?w=456?w=620" alt="barplot" data-image-title="barplot" sizes="(max-width: 620px) 100vw, 620px" data-comments-opened="1" class="wp-image-1554" data-recalc-dims="1">
<p class="wp-caption-text">Single run comparison of 3 loop methods in R.</p>
</div>
<pre>
x = sapply(times, function(i){i[&quot;elapsed&quot;]})
names(x) = substr(names(x), 1, nchar(names(x)) - 8)

par(mar=c(5, 5, 4, 2) + 0.1)
barplot(x, names.arg=names(x),
        main=&quot;Elapsed time on an Intel i5 4460 with 4 cores at 3.2GHz&quot;,
        xlab=&quot;Seconds&quot;, horiz=T, las=1)
par(mar=c(5, 4, 4, 2) + 0.1)
</pre>
<p>Unsurprisingly mclapply is the clear winner. It’s spreading the work across four cores instead of one, so unless the job is very simple it will always be fastest!</p>
<p>Having run this code a few times, I noticed the results are not consistent. Because we’ve been working in code we can examine the variability. I’ve done this by running each method 100 times:</p>
<pre>
times = lapply(1:100, function(i){
   x = list(
      forloop=system.time(
         for (j in f){
            read_clean_write(j)
         }
      ),
      lapply = system.time(
         lapply(f, read_clean_write)
      ),
      mclapply = system.time(
         mclapply(f, mc.cores=4, read_clean_write)
      )
   )
   x = sapply(x, function(k){k[&quot;elapsed&quot;]})
   names(x) = substr(names(x), 1, nchar(names(x))-8)
   x
})

# Tidy
x = lapply(seq_along(times), function(i){
   data.frame(run=i,
              forloop=times[[i]][&quot;forloop&quot;],
              lapply=times[[i]][&quot;lapply&quot;],
              mclapply=times[[i]][&quot;mclapply&quot;])
})
x = do.call(&quot;rbind.data.frame&quot;, x)
</pre>
<p>My poor computer! Now we can plot these results up. I’ve chosen violin plots to help us see the distribution of results:</p>
<div data-shortcode="caption" class="wp-caption"><img data-orig-file="https://scottishsnow.files.wordpress.com/2018/02/violin.png?w=456" data-orig-size="1000,500" data-medium-file="https://scottishsnow.files.wordpress.com/2018/02/violin.png?w=456?w=300" data-attachment-id="1555" data-image-meta="{" data-image-description="" src="https://scottishsnow.files.wordpress.com/2018/02/violin.png?w=456" data-permalink="https://scottishsnow.wordpress.com/2018/02/18/dplyr-lapply-for-loop/violin/" data-large-file="https://scottishsnow.files.wordpress.com/2018/02/violin.png?w=456?w=620" alt="violin" data-image-title="violin" sizes="(max-width: 620px) 100vw, 620px" data-comments-opened="1" class="wp-image-1555" data-recalc-dims="1">
<p class="wp-caption-text">Many runs comparing loop methods in R.</p>
</div>
<pre>
png(&quot;./temp/violin.png&quot;, height=500, width=1000)
x %>%
   gather(variable, value, -run) %>%
   ggplot(aes(variable, value)) +
   geom_violin(fill=&quot;grey70&quot;) +
   labs(title=&quot;100 runs comparing for-loop, lapply and mclapply&quot;,
        x=&quot;&quot;,
        y=&quot;Seconds&quot;) +
   coord_flip() +
   theme_bw() +
   theme(text = element_text(size=20),
         panel.grid=element_blank())
dev.off()
</pre>
<p>Then, we can pull out median values for each:</p>
<table>
<tbody>
<tr>
<td><strong>Method</strong></td>
<td><strong>Time (seconds)</strong></td>
</tr>
<tr>
<td>forloop</td>
<td>1.5255</td>
</tr>
<tr>
<td>lapply</td>
<td>1.5200</td>
</tr>
<tr>
<td>mclapply</td>
<td>0.4515</td>
</tr>
</tbody>
</table>
<pre>

x %>%
   gather(variable, value, -run) %>%
   group_by(variable) %>%
   summarise(median(value))
</pre>
<p>Finally, what do I recommend you use? Occasionally I need to use a for loop (&lt;1 a year), because using lapply is too difficult. It's nice to see I'm <em>probably</em> not incurring much penalty for this heresy. Generally, I believe lapply is an excellent solution, not least because if I need a speed boost I need only call `library(parallel)` and tell mclapply how many cores to use and I’m away. As it seems to be <a rel="nofollow" href="https://robinsones.github.io/The-Importance-of-Sponsorship/" target="_blank">shout-out season</a> (isn’t it always in the great R community?!), this book on <a rel="nofollow" href="https://csgillespie.github.io/efficientR/" target="_blank">efficient R programming</a> by <a rel="nofollow" href="https://twitter.com/csgillespie" target="_blank">Colin</a> and <a rel="nofollow" href="https://twitter.com/robinlovelace" target="_blank">Robin</a> is excellent!</p>
	<p>
<div>
<div>To <strong>leave a comment</strong> for the author, please follow the link and comment on their blog: <strong><a href="https://scottishsnow.wordpress.com/2018/02/18/dplyr-lapply-for-loop/"> R – scottishsnow</a></strong>.</div>
<hr>
<a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers.com</a> offers <strong><a rel="nofollow" href="https://feedburner.google.com/fb/a/mailverify?uri=RBloggers">daily e-mail updates</a></strong> about <a rel="nofollow" href="https://www.r-project.org/" title="The R Project for Statistical Computing">R</a> news and <a rel="nofollow" href="https://www.r-bloggers.com/search/tutorial" title="R tutorials">tutorials</a> on topics such as: <a rel="nofollow" href="https://www.r-bloggers.com/search/data%20science" title="Data science">Data science</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/Big%20Data" title="Big Data">Big Data, <a rel="nofollow" href="https://www.r-users.com/" title="R jobs">R jobs</a>, visualization (<a rel="nofollow" href="https://www.r-bloggers.com/search/ggplot2" title="ggplot and ggplot2 tutorials">ggplot2</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/boxplot" title="Boxplots using lattice and ggplot2 tutorials">Boxplots</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/map" title="Maps and gis">maps</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/animation" title="Animation in R">animation</a>), programming (<a rel="nofollow" href="https://www.r-bloggers.com/search/RStudio" title="RStudio IDE for R">RStudio</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/sweave" title="Sweave and literate programming">Sweave</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/LaTeX" title="LaTeX in R">LaTeX</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/SQL" title="SQL and databases">SQL</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/eclipse" title="Eclipse IDE for R">Eclipse</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/git" title="git and github, Version Control System">git</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/hadoop" title="Large data in R using Hadoop">hadoop</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/Web+Scraping" title="Web Scraping of google, facebook, yahoo, twitter and more using R">Web Scraping</a>) statistics (<a rel="nofollow" href="https://www.r-bloggers.com/search/regression" title="Regressions and ANOVA analysis tutorials">regression</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/PCA" title="principal component analysis tutorial">PCA</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/time+series" title="Time series">time series</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/trading" title="finance trading">trading</a>) and more...
<img alt="" width="1" src="http://feeds.feedburner.com/~r/RBloggers/~4/6uGssVGXmVA" height="1"></a></div>