<?xml version="1.0" encoding="UTF-8"?>
<rss  xmlns:atom="http://www.w3.org/2005/Atom" 
      xmlns:media="http://search.yahoo.com/mrss/" 
      xmlns:content="http://purl.org/rss/1.0/modules/content/" 
      xmlns:dc="http://purl.org/dc/elements/1.1/" 
      version="2.0">
<channel>
<title>Ariel Mundo</title>
<link>https://aimundo.rbind.io/blog/</link>
<atom:link href="https://aimundo.rbind.io/blog/index.xml" rel="self" type="application/rss+xml"/>
<description>Writing on R, reproducible research, data visualization, and scientific manuscripts</description>
<generator>quarto-1.11.9</generator>
<lastBuildDate>Sun, 10 Jul 2022 00:00:00 GMT</lastBuildDate>
<item>
  <title>Writing a manuscript using {bookdown}: A short guide for the life sciences (Part II)</title>
  <link>https://aimundo.rbind.io/blog/2022-07-10-writing-a-manuscript-using-bookdown-2/</link>
  <description><![CDATA[ 




<!-- https://stackoverflow.com/questions/60746090/can-d3-js-visualizations-be-served-using-hugo -->
<section id="quick-refresher" class="level1">
<h1>Quick Refresher</h1>
<p>It took a while for me to get back to this (sorry, a lot of things happening in the world right now). But this is the second entry on my approach on how to use {bookdown} to create a manuscript for a paper in the life sciences (biology, biomedical engineering, etc.).Last time I covered the reasons why we should stop using Word to write papers, and a basic structure for the project.</p>
<p>I realized I needed to create a Repo to keep track of the steps I am describing here, so if you click on the GitHub on top of this blog entry, it should direct you to the Repo that I will be using as an example. So far, our project looks like this:</p>
<p><img src="https://aimundo.rbind.io/blog/2022-07-10-writing-a-manuscript-using-bookdown-2/images/files_panel_directories.png" class="img-fluid"></p>
<p>We have created a project in R (using RStudio), and have directories for figures, data, code, and manuscripts. In this post, I will cover how we can structure the different sections of the paper.</p>
<p><strong>Disclaimer</strong> A large part of the motivation for writing these entries about writing a manuscript comes from my desire to keep a record of the things I’ve done, it is possible that my suggestions here might not align with your needs or your own approach to writing a paper using the tools I describe here. However, I believe the overall description can be useful to people that are interested in creating reproducible documents using R, and you can certainly customize everything to fit your needs!</p>
<p>With that said, let me provide the rationale for the approach I’ll follow here.</p>
</section>
<section id="the-approach" class="level1">
<h1>The Approach</h1>
<p>Let’s say that you have now a directory structure like the one in the image above, and you want to start writing the <em>actual</em> paper. If you have already have clean data files, and scripts for your Stats, what usually needs to be iterated (sometimes, a lot) are the paper sections themselves. That is, you might write a section, get some feedback and re-write such section again, but the data and Stats remain the same. If that is the case, one approach that has worked for me is to create another directory inside the <em>manuscripts</em> directory, which will contain the first version of the paper. Let’s say we call this new subdirectory <em>manuscript_v1</em>. Once you create it, your directory will look like this:</p>
<p><img src="https://aimundo.rbind.io/blog/2022-07-10-writing-a-manuscript-using-bookdown-2/images/manuscript_v1_view.png" class="img-fluid"></p>
<p>Inside this folder, we create another folder (<em>sections</em>) that will contain the file(s) that make the different parts of our manuscript. For example, the typical sections of a paper are:</p>
<ul>
<li>Introduction/Background</li>
<li>Materials and Methods</li>
<li>Results</li>
<li>Discussion</li>
<li>Conclusion</li>
</ul>
<p>Why do we need to create different files? Having a file for each section makes things a lot easier! (The first time I used {bookdown} I started writing the whole paper on a single file and it gets messy and confusing quickly).</p>
<p>So let’s create another folder inside <em>manuscript_v1</em> called <em>sections</em>.</p>
<p>The files that {bookdown} uses to create a document are RMarkdown files (*.Rmd). There are multiple ways to customize an Rmd file (more on that later), but for the time being we just need to create a plain, empty file. To create an empty Rmd file in RStudio, you need to go to File -&gt; New File -&gt; R Markdown -&gt; Click on “Create Empty Document”. To keep things tidy, we will add a number to the files we will create. Once you have created and saved all your files, your directory should look like this:</p>
<p><img src="https://aimundo.rbind.io/blog/2022-07-10-writing-a-manuscript-using-bookdown-2/images/manuscript_Sections.png" class="img-fluid"></p>
<p>Now the fun begins (writing)! How do we write in {bookdown}? Briefly, we only need to add some symbols when writing to indicate the sections of our document. For example, if we go to the <em>01_Introduction.Rmd</em> file, we could start writing something like this:</p>
<p><img src="https://aimundo.rbind.io/blog/2022-07-10-writing-a-manuscript-using-bookdown-2/images/Introduction_writing_example.png" class="img-fluid"></p>
<p>Notice that we added a # before ‘Background’ and ## before ‘Another paragraph’. These symbols basically indicate that they are titles for a section and a subsection, respectively (I won’t cover all the details of Markdown syntax, as an excellent guide can be found <a href="https://bookdown.org/yihui/bookdown/usage.html">here</a>).</p>
<p>The take home point is that once you have created the files, you basically just need to start typing your text and indicate your section and subsection titles. Now, you have created the overall structure of the manuscript (I’ll cover references in another post), but we can’t get a document still, as we haven’t told {bookdown} what formatting options we want.</p>
</section>
<section id="how-we-do-it" class="level1">
<h1>How we do it</h1>
<p>Alright, so we need to create a file that will tell {bookdown} how to assemble the pieces of the manuscript, and what formatting options we want. To do this, we can create an Rmd file on the <em>manuscript_v1</em> directory. The rationale for this is that in this way, we week the parts of the document on a different directory and this avoids having lots of files in the same location (i.e., you will only see and deal with files that are associated with formatting, but the pieces of the paper will be in the <em>sections</em> folder).</p>
<p>Let’s call the file that assembles the whole thing “Complete_paper.Rmd”, and let’s create this file on the <em>manuscript_v1</em> directory. To do this, you will go to File -&gt; New File -&gt; R Markdown <strong>but</strong>, unlike previous times, just click “OK” without changing the default options that appear below:</p>
<p><img src="https://aimundo.rbind.io/blog/2022-07-10-writing-a-manuscript-using-bookdown-2/images/RStudio_menu.png" class="img-fluid"></p>
<p>(Also don’t worry if the Title appears as “Untitled”, we will fix this later).</p>
<p>Once you create the file, it should look like this:</p>
<p><img src="https://aimundo.rbind.io/blog/2022-07-10-writing-a-manuscript-using-bookdown-2/images/Default_Rmd.png" class="img-fluid"></p>
</section>
<section id="the-yaml-header" class="level1">
<h1>The YAML Header</h1>
<p>At the top the document is the YAML header, where we provide formatting instructions to {bookdown}. Notice that the default output at this point is HTML, but generally speaking, we are interested in creating a PDF document so we will edit the YAML section to pass some formatting options that are more convenient for a paper.</p>
<p><strong>NOTE</strong>: The YAML section is very useful but it can be <em>very</em> tricky sometimes because blank spaces <strong>do</strong> matter. If the spaces in a line are wrong, the document may not be compiled or the formatting can be ignored. I can’t count the number of times I had a problem with a document and spent a lot of time trying to figure out what part of the YAML header was wrong!</p>
<p><img src="https://aimundo.rbind.io/blog/2022-07-10-writing-a-manuscript-using-bookdown-2/images/error.gif" class="img-fluid"></p>
<p>You can ignore the content of the default Rmd template, as we will cover how to create figures later on, and we already know how to create title sections and add text.</p>
<p>A modified YAML header looks like this:</p>
<pre><code>title: 'Manuscript'
output:  
  bookdown::pdf_document2:
    fontsize: 12pt
    fontfamily: helvetica
    keep_tex: yes #keep LaTeX file for submission
    fig_caption: yes #allows captions in figures
    toc: false #do not include table of contents
    extra_dependencies:
      subfig: null #allows for subfigures
      breqn: null #line breaks for long equations
      caption: ["font={small}"] #size of the figure captions
    includes:
      in_header: latex_docs/preamble.sty #additional LaTeX formatting
  bookdown::word_document2:
    fig_caption: yes #figure caption
    reference_docx: "docx_template.docx"
    keep_md: yes
  bookdown::html_document2:
    css: "html_docs/style.css" #style for the HTML document
csl: bibliography/american-medical-association.csl #style for references
bibliography: bibliography/refs.bib #references
link-citations: yes #adds links to the citations
urlcolor: blue
'': default
---
</code></pre>
<p>I have added comments to each line to help understand what each option does. In particular, with this YAML header we are able to create a PDF, docx, and HTML outputs if desired. The docx output is very useful for internal reviews, as is possible that other users not familiarized with {bookdown} find it easier to add comments in a Word document (formatting in Word is bad, though).</p>
<p>Additionally, we also now have a couple of additional directories, where formatting instructions for our different outputs will be stored. Note that we are including a LaTeX <em>preamble.sty</em> file. The reason for this is that to get a PDF, {bookdown} creates first a LaTeX file (more about how this is done <a href="https://bookdown.org/yihui/bookdown/pandoc.html">here</a>). You can edit the preamble file to add authors, or change formatting options if desired (each line also has comments to help understand the purpose of each LaTeX package that is being called).</p>
<p>The LaTeX preamble is just added so some options that are by default not available can be used as well (line numbers, double spacing, and a section for authors). LaTeX can be very complex (!), and in my experience, is not used much in the biomed/biology fields, but one of its major advantages is that it automates a lot of the formatting. Don’t freak out, we are trying to use the minimum possible of options to get a paper that is easy to ready and that looks great.</p>
<p>Additionally, we created a directory with a CSS file for HTML output formatting instructions, and added a file called “docx_template.docx”, which {bookdown} will use to create a Word output. Essentially, we have all of our bases covered regarding formatting!</p>
<p>Toward the end of the header, there are two lines that control the references and reference formatting, but we won’t cover that yet.</p>
</section>
<section id="assembling-the-document" class="level1">
<h1>Assembling the Document</h1>
<p>So much for a “short guide” eh? But we’re almost done with this part of the tutorial! The final part we need to look at is the body of our document, where we have added the instructions on how we want to assemble the final document. The body of the document now has some R code chunks that look like this:</p>
<pre><code>{r child='sections/01-Introduction.Rmd'}</code></pre>
<p>The purpose of this chunks is only to call the pieces of our paper in the order we want them to put them in a single document! This is great because in this way you compartmentalize your work, and if a section needs to be fixed, you open the corresponding file, edit it, and compile a new document. With a paper, where there are lot of text, images, and code, a single document can be very hard to navigate. Luckily for us {bookdown} eases the work.</p>
</section>
<section id="knitting-the-document" class="level1">
<h1>Knitting the document</h1>
<p>Finally, we are ready to compile the document! In this post I will only cover the PDF output, as I believe this is the most common type of document that suits a paper. Because in our YAML header we have added the option to create a pdf document (pdf_document2), we can select to create that output by clicking on arrow that is next to the “Knit” button:</p>
<p><img src="https://aimundo.rbind.io/blog/2022-07-10-writing-a-manuscript-using-bookdown-2/images/knit.png" class="img-fluid"></p>
<p>By selecting “Knit to pdf_document2”, we will be able to get our desired PDF output. When the document is ready, a new window will open with the document! With the instructions we provided to {bookdown}, our output looks like this:</p>
<p><img src="https://aimundo.rbind.io/blog/2022-07-10-writing-a-manuscript-using-bookdown-2/images/initial_paper.png" class="img-fluid"></p>
<p>Pretty, isn’t it? Note that each section is numbered, we have line numbers (thanks LaTeX!), double space, and we have a section for the authors and their information. The rest of the sections beyond the Background in this case are empty, but each section and subsection (if added) will be formatted exactly in the same manner. A little lengthy at first, but I guess by now it is clear why using {bookdown} is largely beneficial when creating a paper: you are not fighting with formatting issues, and your document can be replicated if created in any other machine (for example, a reviewer may want to see if is possible to replicate your paper. Trust me, it happened to me!).</p>
</section>
<section id="recap" class="level1">
<h1>Recap</h1>
<p>In this post I covered how to structure the sections of a paper using {bookdown}, adding some formatting options using YAML, and how a PDF output looks. In my next post, I will cover how to create figures using R, where you can combine images, and figures with statistical analyses together!</p>


</section>

 ]]></description>
  <guid>https://aimundo.rbind.io/blog/2022-07-10-writing-a-manuscript-using-bookdown-2/</guid>
  <pubDate>Sun, 10 Jul 2022 00:00:00 GMT</pubDate>
</item>
<item>
  <title>Writing a manuscript using {bookdown}: A short guide for the life sciences (Part I)</title>
  <link>https://aimundo.rbind.io/blog/2022-04-29-writing-a-manuscript-using-bookdown/</link>
  <description><![CDATA[ 




<!-- https://stackoverflow.com/questions/60746090/can-d3-js-visualizations-be-served-using-hugo -->
<section id="why" class="level1">
<h1>Why?</h1>
<p>Let me start this post by sharing the reasons that lead me to write it. I have been an avid R user for some time now, and R has been my default option to clean, analyze, manipulate data, and create graphs. I started using {rmarkdown} to create reproducible reports for my analyses but it never occurred to me that I could write a complete paper with it. However, that changed a couple years ago I wrote a paper about generalized additive models for biomedical data using R. For that paper, I learned about {bookdown}, and how you could create books (or other long publication formats) with it. That was my first experience creating a paper using solely R, and I made many mistakes along the way (also learned a lot).</p>
<p>Specifically, it was hard for me to know how organize the document in a way that made things easier to track. Now, this organization issue probably wouldn’t had been a huge deal had I planned to only share the final paper, but back then I was starting to learn about Open Science and I decided that I had to make the <strong>whole project</strong> reproducible. By trial and error, I figured a way to structure the whole project in such a way that, if I wanted to recreate the whole paper, I only had to click the knit button once.</p>
<p>However, the next roadblock came when I worked in my final paper (as a PhD student) and I realized that probably one of the reasons why {bookdown} is not used more frequently by people in life sciences is because we deal with biological data and images. What I mean by this is that many people know about {rmarkdown}, {bookdown}, and other R packages are good for writing documents; however, these packages are typically associated with documents that are only composed of text and R-generated figures. But when you have imaging data and files (e.g., microscopy images, pictures of equipment, etc), you want to be able to create figures using those files and the first impression is that you can’t do that with {bookdown}. However, as I discovered, you can add imaging data to a document made with {bookdown}! Combining this fact and packages such as {patchwork} and good ’ole {ggplot2} it turns out you can compose great figures that combine statistical analyses, imaging data and more, and you can create a paper that is reproducible with one click. How neat is that?</p>
<section id="purpose-of-this-post" class="level2">
<h2 class="anchored" data-anchor-id="purpose-of-this-post">Purpose of this post</h2>
<p>Based on the experiences I have described before, and the fact that there don’t seem to be much resources on how to use {bookdown} to create reproducible papers in the life sciences (biology, biomedical research, etc.), I wanted to write a short guide that others could use to switch from Word (or Google Docs) to {bookdown} to write manuscripts.</p>
<p>Now, the obliged disclaimer: I am sharing what I have found that works for me. It might be the case that some of the things I describe are not applicable in some situations. But I am sure that with some experimentation, you can tailor the tools I talk about here for your own needs!</p>
</section>
<section id="is-it-worth-it" class="level2">
<h2 class="anchored" data-anchor-id="is-it-worth-it">Is it worth it?</h2>
<p>I realize that someone might say: Why should I change the way I write my papers? Why can’t I just keep using Word?</p>
<p>Well, let me try to answer with another question: Why are you using Word? Is it because is the <strong>best</strong> tool you can use or is it because is the same tool you have been using over and over?. The truth is that most of us working in the most of the STEM fields (Physics and Math being the general exception) stick with writing tools that we learned back in high school (which is when you typically learn to do some acceptable documents in Word).</p>
<p>But as it turns out, those tools are not the best to create documents that can be easily reproduced (opening PC-created Word documents in a Mac, anyone?). And I don’t think I have to convince anyone when I say that for formatting, Word <strong>sucks</strong>. Have you ever tried to move a figure a couple of millimeters in a document that you have painstakingly formatted? If so, your reaction was probably this:</p>
<p><img src="https://aimundo.rbind.io/blog/2022-04-29-writing-a-manuscript-using-bookdown/images/giphy.gif" class="img-fluid"></p>
<p>One of the main benefits of using writing tools like {bookdown} is that, on a basic level, you don’t have to mess with document formatting because this will be automatically handled by the computer. Of course, the learning curve is steeper when switching from Word because your document organization will become programatic, and the first time you do it you will probably miss the blank page-menu-ruler-font tools environment from Word, but trust me when I say that as you progress, you won’t miss these tools anymore because the formatting aspects they handle will be programatically handled in your document by {bookdown}. Additionally, you will always create documents that look <em>good</em> (either PDF or HTML) and if you even want to, you can create a Word output if you want to share your document with someone that is more familiar with that format! (But as always, there are some minor formatting issues…)</p>
<p>Now, eventually you might want to learn <img src="https://latex.codecogs.com/png.latex?%5CLaTeX"> to customize your document, add fancy stuff and be able to debug some issues that come with complex documents, but as a start knowing the basics is enough and will simplify the way you do things.</p>
</section>
<section id="what-we-will-learn" class="level2">
<h2 class="anchored" data-anchor-id="what-we-will-learn">What we will learn</h2>
<p>I will divide this guide in five areas:</p>
<ul>
<li>How to organize the project</li>
<li>Document structure</li>
<li>Creating figures I</li>
<li>Creating figures II</li>
<li>Managing references</li>
</ul>
<p>Each area will cover an aspect of the process of building a paper that is reproducible and that can be created using R. If I decide that there is something else I need to add, I certainly will add more areas to the list.</p>
</section>
<section id="what-you-need" class="level2">
<h2 class="anchored" data-anchor-id="what-you-need">What you need</h2>
<p>Here are the prerequisites to understand (and apply) this guide:</p>
<ul>
<li>Install <a href="https://www.rstudio.com/">RStudio</a> and <a href="https://rstudio-education.github.io/hopr/starting.html">R</a> (this last link has instructions to install both)</li>
<li>Be familiar with R syntax, specifically with {ggplot2} and {patchwork}</li>
<li>Install {bookdown} (instructions can be found <a href="https://bookdown.org/yihui/bookdown/get-started.html">here</a>)</li>
<li>Install a <img src="https://latex.codecogs.com/png.latex?%5CLaTeX"> distribution (for PDF): I recommend using <a href="https://yihui.org/tinytex/">TinyTex</a></li>
</ul>
<p>Don’t feel overwhelmed by the steps above, because they don’t take THAT long to complete, and once you’re done, you’re all set! Also, keep in mind that beyond those prerequisites I make no further assumptions, meaning that I will try to explain each step as clearly as possible. Having said that, let’s start the guide! In this post I will cover Project Organization.</p>
</section>
</section>
<section id="part-1" class="level1">
<h1>Part 1</h1>
<section id="how-to-organize-the-project" class="level2">
<h2 class="anchored" data-anchor-id="how-to-organize-the-project">How to organize the project</h2>
<p>The first thing you want to do is to create a Project for your paper. This will make things easier to navigate, and will save you a lot of trouble later on. Projects are a neat option of RStudio, which is why you needed to install the IDE before starting the guide. To create the project, you need to open RStudio and go to File → New Project → New Directory → New Project. Choose a directory name and the location where you want the project to be (Documents, Desktop, etc.). In this post I won’t cover how to do a project using version control, so ignore the “Create git repository”, and “Use renv with this project” options. Once you have named your project, select “Open in new session” and click <strong>Create Project</strong>.</p>
<p>The main advantage of a Project for a paper is that it allows you to store all your files and run your scripts in the same directory, which is called every time you open the Project. This avoids confusion as you add more files to your paper, and saves you the time required to “Set a working directory”.</p>
</section>
<section id="how-to-structure-your-project" class="level2">
<h2 class="anchored" data-anchor-id="how-to-structure-your-project">How to structure your project?</h2>
<p>Once you click “Create Project” you’ll notice that a new session opens and that in the <strong>Files</strong> panel in RStudio you now have something that looks like this: <img src="https://aimundo.rbind.io/blog/2022-04-29-writing-a-manuscript-using-bookdown/images/files_panel.png" class="img-fluid"></p>
<p>There is nothing else in your project, just a project file (<code>.Rproj</code>) which contains the Project options. Now, the first thing you want to do is to create the directories that will contain the parts of your work. From my experience, is best to “keep things apart”. What I mean by “keeping things apart” is that you create directories for the different components of the paper; for a project that will combine some work in R for statistical analysis (and therefore, some R scripts) and microscopy or other type of imaging data a project could contain the following directories:</p>
<ul>
<li><strong>code</strong>: Here you can store all your scripts, either in the directory itself or in another subdirectory</li>
<li><strong>data</strong>: Stores the raw csv files that you call in your scripts for cleaning, data manipulation and analysis</li>
<li><strong>figures</strong>: Imaging data, as well as schematics and/or diagrams</li>
<li><strong>manuscripts</strong>: Here you can store successive iterations of your paper as you make corrections.</li>
</ul>
<p>If you create these folders, your project will look like this:</p>
<p><img src="https://aimundo.rbind.io/blog/2022-04-29-writing-a-manuscript-using-bookdown/images/files_panel_directories.png" class="img-fluid"></p>
<p>The rationale for the different directories is that typically, what tends to change (sometimes a lot) is the written part of the manuscript itself, but the data and the statistical analyses are usually iterated a few times and after that, they just need to be incorporated into the manuscript. The same idea holds for the “figures” directory, where you create the figures (this can be in a different environment such as Inkscape, BioRender, etc. ) and later on you only need to incorporate them into the manuscript.</p>
<p>Let’s assume an scenario where you have completed your data analyses and figures, and have some scripts in “code” that use the csv files in the “data” directory. Now you are ready to start writing your manuscript. The way I have found that this work best is to create a directory within “manuscripts” that you can call “paper_v1”. You finish this first draft and send it for internal review (your advisor in the case of a grad student, collaborators, etc.). You get some feedback and decide you want to start v2 of the paper.</p>
<p>Here is where the advantage of “keeping this apart” apparent, because all you need to do is create another directory within “manuscripts” for the second draft (let’s assume this directory is called “paper_v2”), and modify the written part of the manuscript. The neat thing here is that your code and data stay in the same directories and they just need to be called again (I will talk in detail about this later on), there is no need of re-writring scripts and moving files with code and data over and over again!</p>
<p><img src="https://aimundo.rbind.io/blog/2022-04-29-writing-a-manuscript-using-bookdown/images/smart.gif" class="img-fluid"></p>
</section>
<section id="summing-it-up" class="level2">
<h2 class="anchored" data-anchor-id="summing-it-up">Summing it up</h2>
<p>In this first post, I covered the benefits of using {bookdown} to create reproducible (academic) papers, and how “keeping this apart” by creating directories for your data, code and manuscript files makes thing easier to follow. In the next post, I will cover how to structure the paper itself! See ya!</p>


</section>
</section>

 ]]></description>
  <guid>https://aimundo.rbind.io/blog/2022-04-29-writing-a-manuscript-using-bookdown/</guid>
  <pubDate>Fri, 29 Apr 2022 00:00:00 GMT</pubDate>
</item>
<item>
  <title>First post after a long hiatus? Make a map!</title>
  <link>https://aimundo.rbind.io/blog/2021-11-09-30-day-map-challenge/</link>
  <description><![CDATA[ 




<!-- https://stackoverflow.com/questions/60746090/can-d3-js-visualizations-be-served-using-hugo -->
<p>I have been in a long hiatus from posting anything on my website. Just when I thought I was gaining some momentum with making regular posts a lot of things started to happen (experiments, paper submissions, corrections…). So today’s post is going to be simple. I saw Amit Levinson’s <a href="https://twitter.com/Amit_Levinson/status/1457940340149739520">Tweet</a> in the #30DayMapChallenge about Israel’s 3d elevation map and it inspired me to do something similar. My goal here was to create an elevation map of my home country, Guatemala.</p>
<p>First, I had to get the <code>sph</code> file with the map data. I used the data provided by <a href="https://www.diva-gis.org/">DIVA_GIS</a>, unzipped the contents and placed everything in a folder. I am by no means a map expert, but it seems that not only the <code>.shp</code> file is necessary to visualize the map; the other files (<code>dbf</code>, <code>prj</code>, etc) are also necessary. So first we load our packages, and read the map data.</p>
<p>The syntax was hard for me to understand (a geocomputation illiterate), but I found information <a href="https://geocompr.robinlovelace.net/spatial-class.html#crs-intro">here</a> about the puzzling <code>4326</code> in the <code>st_transform</code>line. It basically indicates which Coordinate Reference System (CRS) is to be used (4326 is the code for the Spatial Reference System Identifier EPSG).</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb1" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb1-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">library</span>(elevatr)</span>
<span id="cb1-2"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">library</span>(rayshader)</span>
<span id="cb1-3"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">library</span>(sf)</span>
<span id="cb1-4"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">library</span>(here)</span>
<span id="cb1-5"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">library</span>(rgdal)</span>
<span id="cb1-6"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">library</span>(magick)</span>
<span id="cb1-7"></span>
<span id="cb1-8">gtdata<span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">read_sf</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"content/blog/2021-11-09-30-day-map-challenge/data/GTM_adm0.shp"</span>)</span>
<span id="cb1-9"></span>
<span id="cb1-10"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">#Transform to st. Spatial Reference System Identifier (SRID). EPSG:4326</span></span>
<span id="cb1-11">gtdata<span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">st_transform</span>(gtdata,<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4326</span>)</span></code></pre></div></div>
</div>
<p>And now we move to the fun part. Using <code>{rayshader}</code> we will first get the raster elevation data using <code>get_elev_raster</code> and then transform the raster data to a matrix using <code>raster_to_matrix</code>. Finally, we will plot the map in 3d and save it.</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb2" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb2-1"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">#elevation data</span></span>
<span id="cb2-2"></span>
<span id="cb2-3">gtraster <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">get_elev_raster</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">locations =</span> gtdata, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">z =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">9</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">clip =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"locations"</span>)</span>
<span id="cb2-4"></span>
<span id="cb2-5"> <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">#Convert to matrix for rayshader plotting</span></span>
<span id="cb2-6">gtrayshader <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">raster_to_matrix</span>(gtraster)</span>
<span id="cb2-7"></span>
<span id="cb2-8"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">#plot in 3d</span></span>
<span id="cb2-9">gtrayshader <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%&gt;%</span> </span>
<span id="cb2-10">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sphere_shade</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">texture =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"bw"</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%&gt;%</span> </span>
<span id="cb2-11">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">plot_3d</span>(gtrayshader, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">zscale =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">50</span>, </span>
<span id="cb2-12">          <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">fov =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, </span>
<span id="cb2-13">          <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">theta =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, </span>
<span id="cb2-14">          <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">zoom =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.9</span>, </span>
<span id="cb2-15">          <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">phi =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">50</span>, </span>
<span id="cb2-16">          <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">windowsize =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1000</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1000</span>))</span>
<span id="cb2-17"></span>
<span id="cb2-18"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">#save it</span></span>
<span id="cb2-19"> </span>
<span id="cb2-20"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">render_snapshot</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">filename=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"content/blog/2021-11-09-30-day-map-challenge/Guatemala"</span>,</span>
<span id="cb2-21">                <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">title_text =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Elevation map of  Guatemala"</span>,</span>
<span id="cb2-22">                <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">title_offset =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">150</span>,<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">850</span>),</span>
<span id="cb2-23">                <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">title_size =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">50</span>,</span>
<span id="cb2-24">                <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">title_font =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'Helvetica'</span></span>
<span id="cb2-25">                )</span></code></pre></div></div>
</div>
<p>And the result? This beauty:</p>
<p><img src="https://aimundo.rbind.io/blog/2021-11-09-30-day-map-challenge/Guatemala.png" class="img-fluid"></p>
<p>And I have to say, achieving this in 9 lines of code (minus loading packages and function options) is truly impressive! You can check the excellent <code>{rayshader}</code> documentation <a href="https://www.rayshader.com/">here</a> here.</p>
<p>Well, that is all for now, but I will be back soon (hopefully) with another post.</p>



 ]]></description>
  <guid>https://aimundo.rbind.io/blog/2021-11-09-30-day-map-challenge/</guid>
  <pubDate>Tue, 09 Nov 2021 00:00:00 GMT</pubDate>
</item>
<item>
  <title>Adding JavaScript animations using p5.js</title>
  <link>https://aimundo.rbind.io/blog/2021-07-25-testing-javascript-visualizations/</link>
  <description><![CDATA[ 




<!-- https://stackoverflow.com/questions/60746090/can-d3-js-visualizations-be-served-using-hugo -->
<p>Disclaimer: I am no Javascript expert. The target audience for this post are those that want to add something <em>extra</em> to their site, but that like me, have very little knowledge of JavaScript.</p>
<p>But let me say this: it’s doable, and that is the beauty of the Hugo Apéro theme, it is very well organized and makes it easy to follow!</p>
<section id="how-the-idea-started" class="level3">
<h3 class="anchored" data-anchor-id="how-the-idea-started">How the idea started</h3>
<p>A couple weeks ago I read a Tweet from Alison Presmanes Hill where she commented on the beauty of Deisy Gysi’s <a href="https://deisygysi.github.io/">site</a>. And the site is truly beautiful, the background is mesmerizing! I was intrigued on how such animations could be implemented in a Hugo site.</p>
<p>I am no programming wizard (faaaar from it), but if there’s <strong>one thing</strong> I have learned during my PhD is to find information. So, I decided to start my quest by googling “hugo background animation”. Among the first results that I could see, there was one that caught my eye: “Customizing a Hugo theme with an animated P5.js background” (which can be found <a href="https://nathan.exchange/posts/p5js-background-for-hugo/">here</a>).</p>
<p>Upon doing some reading two things were clear:</p>
<ul>
<li><p>Such customization required JavaScript</p></li>
<li><p>The post was a little bit old (2018).</p></li>
</ul>
<p>From seeing the structure of the folders described in the post I could tell that the Apero theme did not have the same structure. Moreover, because I knew that Hugo themes tend to have multiple changes over time, I was afraid that by making the proposed changes in the post I would end up messing things too much (it had happened before and I ended up burning everything to the ground from the Hugo Academic theme and migrated to the Apero theme, which had substantial benefits).</p>
<p>But one thing was clear, this was doable. However, the first thing I wanted to know was what was this <code>p5.js</code> thing. Well, turns out that <a href="https://p5js.org/">p5</a> is a JavaScript (JS) library for creative coding. Watching the examples on the site was mindblowing! Take some time and look them up, because although most of them are in plain black and white, it’s easy to see the potential of using <code>p5</code> to create beautiful artwork.</p>
<p>One of the examples is called <a href="https://p5js.org/examples/simulate-particles.html">“particles”</a>, and when I saw it I realized that it was very similar to Geisy’s website background. Actually, there is a library called “particles.js” that makes it easy to use and customize (see <a href="https://vincentgarreau.com/particles.js/">here</a>).</p>
</section>
<section id="the-quest-continues" class="level3">
<h3 class="anchored" data-anchor-id="the-quest-continues">The quest continues</h3>
<p>I had a starting point, I wanted to use <code>p5.js</code>, but I could not find a thorough explanation of how to use the library on a Hugo site. I noticed that some people had asked similar questions in the Hugo community, but honestly I lacked the programming experience to understand the explanations given, or they were too vague (multiple times I found something along the lines of “can be implemented later”).</p>
<p>However, one thing became apparent from reading these posts: If you are going to use JS on a Hugo site, the scripts need to be in a specific folder. I noticed most of the posts made reference to the root <strong>static/</strong> folder as the place where <code>.js</code> files need to be placed. I also ended up learning that because of the way Hugo works, it is recommended that any changes you make on your site regarding style (CSS, fonts, etc.) are to be placed in folders in the root directory (such as <code>static</code>, <code>assets</code>, etc), rather than altering the theme itself.</p>
<p>When Hugo loads the site it looks on the root folder first and any changes you have made regarding style override the default theme settings. And because is easy to keep track of changes and additions that are made on the folders you create on the root directory rather than messing with the <code>themes/hugo-apero</code> folders, this saves you multiple headeaches later, which is something I can attest.</p>
<p>Back to the question at hand, I stumbled on <a href="https://stackoverflow.com/questions/60746090/can-d3-js-visualizations-be-served-using-hugo">this</a> post, where someone asked about using something called <code>D3.js</code> in a Hugo site. Now, <code>D3.js</code> is not <code>p5.js</code> but there is a saying in Spanish that goes <em>un diablo se parece a otro</em>, which basically means that sometimes you can confuse two persons that look alike. In my naive mind, <code>D3.js</code> was close enough to <code>p5.js</code> and I thought that the procedure to implement the first had to work for the latter.</p>
</section>
<section id="what-you-need-to-do" class="level3">
<h3 class="anchored" data-anchor-id="what-you-need-to-do">What you need to do</h3>
<p>OK, so here is where things get interesting. Say you want to add the “particles” example from p5.js to a blog post. The first thing you need to do is to copy the code that appears below the example on the <a href="https://p5js.org/examples/simulate-particles.html">site</a> and paste it in a file that we will call <code>particles.js</code>. The file needs to exist in a root folder called <code>static</code>, and for the sake of being organized we will further place it in a folder called <code>js</code>. In other words, the path is <code>../static/js/particles.js</code></p>
<p>So far, so good. Now, say you create a new blog post, which you will coveniently create using the Blogdown ‘new post’ Addin in RStudio. Say you create a blog post titled “Testing p5.js” and that you are going to make it using a <code>.Rmd</code> file.</p>
<p>Below the YAML header, you can write some text:</p>
<pre><code>---
title: Trying a p5.js animation
author: ''
date: ''
slug: []
categories: []
tags: []
---

### Some clever text</code></pre>
<p>Because HTML is supported in RMarkdown, first we need to call the p5.js library:</p>
<pre><code>&lt;script src="https://cdn.jsdelivr.net/npm/p5@1.4.0/lib/p5.js"&gt;&lt;/script&gt; &lt;!-- load p5.js from CDN--&gt; </code></pre>
<p>And then we will call our <code>particles.js</code> script:</p>
<pre><code>&lt;script src = "/js/particles.js"&gt;&lt;/script&gt; &lt;!-- this will pick our script  --&gt;</code></pre>
<p>Just by adding those two lines, you should be able to see the animation running <em>at the bottom</em> of the page.</p>
<p>By default, <code>p5.js</code> objects (also called “sketches”) are added at the bottom of the page. Say you want to write some text, add a <code>p5.js</code> animation and continue writing below. How do you achieve this?</p>
<p>You need to do two things:</p>
<ul>
<li>In the <code>.js</code> animation file you created (in this case <code>particles.js</code>) and that now lives in <code>static/</code> you need to find this line (assuming you haven’t changed anything yet):</li>
</ul>
<pre><code>createCanvas(720, 400);</code></pre>
<p>And change it to:</p>
<pre><code>var canvas = createCanvas(700, 470); //make it an object
canvas.parent('particles-holder');</code></pre>
<p>As I said before, I am no JS expert, but intuitively, we’re making the canvas a type of “object” we can use a function on. <code>p5.Element.parent()</code> function allows to move the sketch inside an HTML file. So now, when we call it in our blog post, you can have something like this:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb6" style="background: #f1f3f5;"><pre class="sourceCode markdown code-with-copy"><code class="sourceCode markdown"><span id="cb6-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">#### Some clever text</span></span>
<span id="cb6-2"></span>
<span id="cb6-3">Here we have a particle simulation from p5.js.</span>
<span id="cb6-4"></span>
<span id="cb6-5"><span class="in" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">```{=html}</span></span>
<span id="cb6-6"><span class="in" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;div id="particles-holder"&gt;&lt;/div&gt;</span></span>
<span id="cb6-7"><span class="in" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;script src="https://cdn.jsdelivr.net/npm/p5@1.4.0/lib/p5.min.js"&gt;&lt;/script&gt;</span></span>
<span id="cb6-8"><span class="in" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;script src="/js/particles.js"&gt;&lt;/script&gt;</span></span>
<span id="cb6-9"><span class="in" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">```</span></span>
<span id="cb6-10"></span>
<span id="cb6-11">More text to come!</span></code></pre></div></div>
<p>The result is what you see below, we have some text before the sketch, we call the sketch, and we write more text below.</p>
<div id="particles-holder"></div>
<script src="https://cdn.jsdelivr.net/npm/p5@1.4.0/lib/p5.min.js"></script>
<script src="../../js/particles.js"></script>
<p>As you can see, there is some work to do but it is honestly very rewardint to add such cool animations and visualizations to your site.</p>
<p>Final thoughts:</p>
<ul>
<li><p>There are multiple ways of doing this. This is what worked for me this time, but I am sure more improvements can be done (as when you want multiple sketches on a page, which is covered <a href="https://joemckaystudio.com/multisketches/">here</a>).</p></li>
<li><p>I recently migrated to the Hugo Apéro theme. I have to say that it is extremely well done. The Wowchemy Academic theme was usable, but things were confusing at times and documentation was, well, poor. It is nice to see a theme that makes customizations easy, and that is well structured.</p></li>
</ul>


</section>

 ]]></description>
  <guid>https://aimundo.rbind.io/blog/2021-07-25-testing-javascript-visualizations/</guid>
  <pubDate>Sun, 25 Jul 2021 00:00:00 GMT</pubDate>
</item>
<item>
  <title>Panicking over References</title>
  <link>https://aimundo.rbind.io/blog/2021-06-23-panicking-over-references/</link>
  <description><![CDATA[ 




<p>A couple days ago I was finishing the submission of a paper I had been working on for a while. It was quite the ride, because I used the <code>pdf_document2</code> to create the paper, but the journal I submitted it to required that I use their <img src="https://latex.codecogs.com/png.latex?%5CLaTeX"> template. I might write another post about the process, but in synthesis, I was able to transfer the structure of my file to a template provided by the <code>rticles</code> package. From there I generated a <code>Tex</code> file with the main manuscript and uploaded all the auxiliary files to the journal submission portal. However, when I had to check the final proof of the document I noticed that it did not contain the references, rather having just <img src="https://latex.codecogs.com/png.latex?%5C:%5E%7B????%7D"> in all the entries.</p>
<p>This was puzzling because I had already knitted a PDF version of the document and the references were showing up in that file. I chatted with someone from the Support Department of the journal and upon checking my files, these lines appeared in the chat window:</p>
<p><em>You need to manually add the references to your TeX file, remove the line where you call your ‘refs.bib’ file and upload the file again to the journal website. Please see this</em>: https://en.wikibooks.org/wiki/LaTeX/Manually_Managing_References</p>
<p>Upon reading the first lines of the <img src="https://latex.codecogs.com/png.latex?%5CLaTeX"> wikibook it was apparent that this was going to be a painful task. The reason being that the format of a <code>.bib</code> file is as follows:</p>
<pre><code>@article{lander2011,
  doi = {10.1038/nature09792},
  url = {https://doi.org/10.1038/nature09792},
  year = {2011},
  month = feb,
  publisher = {Springer Science and Business Media {LLC}},
  volume = {470},
  number = {7333},
  pages = {187--197},
  author = {Eric S. Lander},
  title = {Initial impact of the sequencing of the human genome},
  journal = {Nature}
}</code></pre>
<p>But the actual entry in a <img src="https://latex.codecogs.com/png.latex?%5CLaTeX"> document depends on the Reference style used. A SAGE Vancouver entry of the same reference would look like this (and I am ignoring the formatting commands that would have to appear before):</p>
<pre><code>\bibitem{lander2011}
Lander, ES
\newblock Initial impact of the sequencing of the human genome
\newblock \emph{Nature} 2011; 470(7333):
  187-197.
\newblock \doi{10.1038/nature09792}.
\newblock \urlprefix\url{https://doi.org/10.1038/nature09792}</code></pre>
<p>Manually doing all the changes would be <strong>rather</strong> painful, and with a long list of references the chances of making a mistake are huge. However, something made me think that an automated version to do this <em>had</em> to exist (keep in mind that I am no <img src="https://latex.codecogs.com/png.latex?%5CLaTeX"> expert).</p>
<p>I suddenly remembered that a couple days before, I was messing around with <a href="https://www.overleaf.com"><strong>Overleaf</strong></a> (the reasons why I was doing this are not important for the purpose of this post), and that the <code>.bbl</code> file, which is basically the <img src="https://latex.codecogs.com/png.latex?%5CLaTeX"> formatted version of a <code>.bib</code> file is saved when a document is compiled in Overleaf, and can be downloaded. So to try this, I created a new project in Overleaf, uploaded my <code>.TeX</code>, <code>.csl</code>, <code>.bib</code> and <code>.bst</code> files and compiled the document. Once it was correctly compiled and I checked that the references were on the document, I followed <a href="https://www.overleaf.com/learn/how-to/Exporting_your_work_from_Overleaf#Downloading_with_.bbl_file.2C_for_journal_submission"><strong>these</strong></a> instructions to donwload the auxiliary <code>.bbl</code> file, which had all the references in the appropiate <img src="https://latex.codecogs.com/png.latex?%5CLaTeX"> format for the journal.</p>
<p>Then, I basically opened the <code>.bbl</code> file in RStudio, and copied the entire content of the file at the end of my <code>.tex</code> file (the main manuscript for submission). I made sure to delete the line in the file that was not working to import the references:</p>
<pre><code>\bibliography{refs.bib}</code></pre>
<p>And sure enough, when I uploade this updated <code>.tex</code> file to the journal submission webiste, my references worked!</p>
<p>There is always something new to learn with <img src="https://latex.codecogs.com/png.latex?%5CLaTeX"> and sometimes it can be kinda… fun.</p>



 ]]></description>
  <category>LaTeX</category>
  <category>Bibtex</category>
  <guid>https://aimundo.rbind.io/blog/2021-06-23-panicking-over-references/</guid>
  <pubDate>Wed, 23 Jun 2021 00:00:00 GMT</pubDate>
</item>
<item>
  <title>Building a manuscript using Bookdown</title>
  <link>https://aimundo.rbind.io/blog/2021-06-04-building-a-manuscript-using-bookdown/</link>
  <description><![CDATA[ 




<section id="why" class="level2">
<h2 class="anchored" data-anchor-id="why">Why?</h2>
<p>This is the second post about working with <code>Bookdown</code> and my experience on the process (first post is <a href="http://aimundo.rbind.io/post/using-bookdown-different-authors-in-a-document/"><strong>here</strong></a>). This post focuses on how I found that was easy to compartmentalize my work and some tips I learned along the way (I will probably write about some other things in the future as well).</p>
</section>
<section id="use-chapters" class="level1">
<h1>Use “chapters”</h1>
<p>When I started working with <code>Bookdown</code> I was making a single document for my manuscript. Doing it in that way was manageable at the beginning, but as I wrote more and added more code, scrolling down started to become painful (specially after I realized one day that I was at about 1000 lines in length between code/text). I decided that I wanted to break the document in pieces, but I didn’t know how. Reading through the Web I came to realize that you can piece a <code>Bookdown</code> document using the <code>child</code> option (see <a href="https://bookdown.org/yihui/rmarkdown-cookbook/child-document.html"><strong>here</strong></a> for a thorough description). The <code>child</code> option means that you will break your document in “Chapters” but they will be knitted in a single document when you compile the PDF/HTML output. For this to work you need in the same working directory:</p>
<ul>
<li>A “central” document that will contain the YAML header and the instructions to call all the other documents.</li>
<li>All your “chapters”</li>
</ul>
<p>The “central” document will contain all the formatting instructions (YAML header with bibliography, references styles, <img src="https://latex.codecogs.com/png.latex?%5CLaTeX"> options, etc) and chunks of code where you call the “chapters”. Suppose you call this “central” document <code>Main.Rmd</code>, and that you have in the same directory two “chapters”: <code>Chapter 1.Rmd</code> and <code>Chapter 2.Rmd</code>.</p>
<p>In <code>Main.Rmd</code>, after they YAML header and the chunk where the <code>knitr</code> options are specified, you need to add the chunks that will call the chapters, like this:</p>
<pre><code>```{r child='Chapter 1.Rmd'} `r ''`
```</code></pre>
<pre><code>```{r child='Chapter 2.Rmd'} `r ''`
```</code></pre>
<p>The very convenient thing about using this approach, is that you can move across the chapters and find things <em>way</em> more quickly than using a single document; you can also check bugs in your code without constantly scrolling up and down. Keep in mind that all your packages need to be loaded in <code>Main.Rmd</code>, the “chapters” do <strong>not</strong> have a YAML header or an R chunk for options, you can start them just with text. If you were to open the file for the first chapter it would look like this:</p>
<ul>
<li>Chapter 1.Rmd</li>
</ul>
<pre class="text"><code># Chapter 1: Introduction

In this section we will review the current status of the field of interest.</code></pre>
<section id="things-to-keep-in-mind" class="level2">
<h2 class="anchored" data-anchor-id="things-to-keep-in-mind">Things to keep in mind</h2>
<p>Below are a few things that are important to keep in mind when you are working with the <code>child</code> option in <code>Bookdown</code>:</p>
<ul>
<li><p>The complete document should be knitted from <code>Main.Rmd</code>. I sometimes made the mistake of trying to knit from one of the “chapter” files, but it does not work because all the packages and the YAML hearder are in <code>Main.Rmd</code> so it is there where you have to knit your document.</p></li>
<li><p>If you want to debug some code, remember to always run the chunk in <code>Main.Rmd</code> that contains the libraries and any other things you need for your document to work. Specially if you are using a global theme for colors, for example. Because if you try to debug some <code>ggplot2</code> figures in <code>Chapter 1.Rmd</code> that use the global theme, you won’t be able to do it unless those settings are loaded in the environment.</p></li>
<li><p>Learn to use <img src="https://latex.codecogs.com/png.latex?%5CLaTeX"> to control the formatting of the chapters. For example, I noticed that for my manuscript some of the Figures were being pushed to the next chapter by default, when I wanted them to stay in the chapter they belonged to. Options such as <code>\FloatBarrier</code>, which is from the <img src="https://latex.codecogs.com/png.latex?%5CLaTeX"> package <strong>float</strong>, allows you keep the figures in the chapter where they were created, therefore avoiding any weird Figure misplacing.</p></li>
</ul>
<p>There are many options in <img src="https://latex.codecogs.com/png.latex?%5CLaTeX"> that allow you to control the formatting of your document, so learning how to use packages is quite useful.</p>
<p>Alright, that’s it for now!</p>


</section>
</section>

 ]]></description>
  <category>R</category>
  <category>bookdown</category>
  <category>LaTeX</category>
  <guid>https://aimundo.rbind.io/blog/2021-06-04-building-a-manuscript-using-bookdown/</guid>
  <pubDate>Fri, 04 Jun 2021 00:00:00 GMT</pubDate>
</item>
<item>
  <title>Using Bookdown: Different authors in a document</title>
  <link>https://aimundo.rbind.io/blog/2021-05-19-using-bookdown-different-authors-in-a-document/</link>
  <description><![CDATA[ 




<p>Disclaimer: I am writing this Blog in hopes that what I’ve learned helps someone else, but I also do it as a cathartic component of the learning process. So dear reader, please bear with me while I narrate my journey…</p>
<section id="why-dont-you-try-rmarkdown-and-moving-to-bookdown" class="level1">
<h1>“Why don’t you try RMarkdown?” and moving to Bookdown</h1>
<p>A while ago I started to work on a manuscript, and during a meeting with the co-authors one of them said “Why don’t you try RMarkdown to write this project?”. Until that moment, I had only used Word to write scientific documents, and a quick look on the Internet confirmed my initial suspicion that using RMarkdown was a complete different experience than using Word. Nonetheless, I also had a feeling that learning to do things in RMarkdown <em>had</em> to be beneficial, so I decided that it was worth to give it a shot. If I didn’t like how things were going after a week, I would go back to Word.</p>
<p>Fast forward a couple days later and I’m starting to understand how things work on RMarkdown, and I also realize that I need to cross-reference an equation in the manuscript. A Google search indicates that to do this, I should probably use <a href="https://bookdown.org/yihui/rmarkdown/"><strong>Bookdown</strong></a>. A quick glimpse on the Bookdown manual also indicates that Bookdown offers more capabilities than RMarkdown to reference equations and figures. So I start working on Bookdown. As I work on the manuscript more and more, I find that using Bookdown is substantially more beneficial to write a document than Word. Equations? Easy, and unlike the equations made in Word, here they look gorgeous, textbook-like. Citations? A small learning curve, but you understand what you are doing and control the amount of information you have for each reference. Above all, one of the major advantages is that when creating figures in R you don’t have to mess with importing the figure and fighting with its placement in the document, which is always a pain in Word!</p>
<p>However, about a week ago I decided to work on some minor things, and had to add the author information on the manuscript (which hencefort I will call <code>Manuscript.Rmd</code>). There are three authors, two of which (including myself) are from the same academic institution. I try the option of listing the authors in the YAML header as the Bookdown manual suggests (title and author information in this case are fake):</p>
<pre><code>---
title: '**A longitudinal analysis of Twitter trends in the year 2020**'
subtitle: _Political and sociological considerations_
author:
- Benicio del Ox^[Department of Sociology, University of the Insula]
- Jake A. Motaungh^[Department of Sociology, University of the Insula]
- Frederick P. Montego^[Department of Psychology, University of Mars]
---</code></pre>
<p>The main problem here is that when rendered, the header looked like this: <img src="https://aimundo.rbind.io/blog/2021-05-19-using-bookdown-different-authors-in-a-document/Header_1.JPG" class="img-fluid" alt="h-1"></p>
<p>While the footnote looked like this: <img src="https://aimundo.rbind.io/blog/2021-05-19-using-bookdown-different-authors-in-a-document/footnote_1.JPG" class="img-fluid" alt="footnote-1"></p>
<p>Its clear that every author was being assigned a “different” institution. I was naive enough to think that Bookdown would “detect and merge” the affiliation of twor or more authors when it was the same, but that was clearly not the case.</p>
<p>I couldn’t find a satisfactory answer to this problem in the Bookdown Cookbook or in the forums I consulted, but what I did found was that there is a <img src="https://latex.codecogs.com/png.latex?%5CLaTeX"> package called <code>authblk</code> that allows for better control on the author information. This search also lead me to <a href="https://www.r-bloggers.com/2020/12/author-with-affiliation-in-bookdown-html-and-pdf/"><strong>this</strong></a> post on Rbloggers with a proposed solution on how to use <code>authblk</code> in a Bookdown document.</p>
<p>However, the syntax offered by the post didn’t work for me, and after repeatedly trying to make the YAML header to behave (YAML headers are quite temperamental and picky about indentations!) I started to think that I would probably have to submit a question about this issue in some specialized forum (which would involve creating a <code>reprex</code>, creating an account, registering, and the list goes on…).</p>
<p>After reading for a while again, I discover (yes, I know this is pretty well known to almost anyone, but it felt like a great discover to me, nonetheless) that more control over the creation of the document can be achieved by using a <code>.sty</code> file. In short, the <code>.sty</code> file can contain some <img src="https://latex.codecogs.com/png.latex?%5CLaTeX"> code that allows to customize the final document (longer explanation <a href="http://dw.tug.org/pracjourn/2005-3/asknelly/nelly-sty-&amp;-cls.pdf"><strong>here</strong></a>). This discovery was really convenient as this approach would allow me add line numbers, which is something I also wanted to do on the document.</p>
<p>So I proceeded as follows:</p>
<ul>
<li><p>Creating a <code>.sty</code> file called “preamble” that was the same directory where <code>Manuscript.Rmd</code> was located.</p></li>
<li><p>In <code>preamble.sty</code>:</p></li>
</ul>
<pre><code>\usepackage{lineno}
\usepackage{authblk}

%command for the package lineno to put line numbers in the manuscript
\linenumbers

%authors
\author[1]{Benicio del Ox}
\author[2]{Jake A. Motaungh}
\author[1]{Frederick P. Montego}
\affil[1]{\footnotesize Department of Sociology, University of the Insula}
\affil[2]{\footnotesize Department of Psychology, University of Mars}
</code></pre>
<p>Then, in the YAML header of <code>Manuscript.Rmd</code> I added two lines to indicate that <img src="https://latex.codecogs.com/png.latex?%5CLaTeX"> code is in <code>preamble.sty</code>. The two lines are <code>includes</code> and <code>in_header</code>:</p>
<pre><code>---
title: '**A longitudinal analysis of Twitter trends in the year 2020**'
subtitle: _Political and sociological considerations_
output:  
  bookdown::pdf_document2:
    keep_tex: yes
    includes:
      in_header: preamble.sty
---
</code></pre>
<p>Alright! And the document looked like… <img src="https://aimundo.rbind.io/blog/2021-05-19-using-bookdown-different-authors-in-a-document/Header_2.JPG" class="img-fluid" alt="h-2"></p>
<p>Huh… that was odd. It was nice to see that the document had line numbers, but you can notice that there is an additional “and” after the last author along with a superscript for the affiliation. This was the most frustrating thing, I am no <img src="https://latex.codecogs.com/png.latex?%5CLaTeX"> expert and I couldn’t find the cause of the problem, although I suspected that there was a conflict between the Pandoc LaTeX template and what the <code>authblk</code> package was doing. For this one, I was out of ideas after several hours of trying to fix the issue and decided to submit an issue on the <code>Bookdown</code> GitHub <a href="https://github.com/rstudio/bookdown"><strong>site</strong></a>.</p>
<p>I got a very detailed response from the <code>Bookdown</code> team the next day (yesterday). So I decided to add the explanation and the solution here before I forget. It goes like this: RMarkdown uses a Pandoc <img src="https://latex.codecogs.com/png.latex?%5CLaTeX"> template (which can be found <a href="https://github.com/jgm/pandoc/blob/master/data/templates/default.latex"><strong>here</strong></a>)to build documents, and in that template there is an ‘author’ line that includes an <code>\and</code> command. In that template the field is not conditional, meaning that it will always appear even if you already have the information in a separate <code>.sty</code> or <code>.tex</code> file. Because in this case I have no ‘author’ information to pass to the template (as the author information is in the <code>.sty</code> file) the template author field remain blank but the <code>\and</code> will always appear.</p>
<p>There are two solutions which the <code>Bookdown</code> team provided (<a href="https://github.com/rstudio/bookdown/issues/1158"><strong>here</strong></a>):</p>
<ul>
<li>Use a custom LaTeX template that does not include the <code>\author</code> line.</li>
<li>Add a function in the <code>.Rmd</code> document that post-processes the <img src="https://latex.codecogs.com/png.latex?%5CLaTeX"> file through <code>bookdown.post.latex</code>(more information about this function <a href="https://github.com/rstudio/bookdown/blob/master/R/latex.R"><strong>here</strong></a>)</li>
</ul>
<p>I tried both options. In the first case, you only need to edit the original template, save with a custom name in the same directory where your <code>.Rmd</code> file is and call it in the YAML header like this:</p>
<pre><code>bookdown::pdf_document2:
  template: my-template.tex</code></pre>
<p>However, it seems that maintaining a custom template can be tricky if there are updates over time. So I also tried the second option, which is the function provided by the <code>Bookdown</code> team and that you have to place in a <code>setup</code> chunk at the beginning of the document. It can also be placed in the chunk where the <code>knitr::opts</code> line would be. The function is:</p>
<pre><code>remove_author &lt;- function(x) {
  # identify empty author line
  i &lt;- grep("^\\\\author\\{\\}$", x)
  # be sure it is the one pandoc inserts
  if(length(i) != 0 &amp;&amp; grepl('^\\\\date\\{', x[i+1])) x &lt;- x[-i]
  x
}
options(bookdown.post.latex = remove_author)
</code></pre>
<p>In this way, the default template is called, but the function will remove the <code>author</code> line. I found that this worked nicely, with the advantage of not having to worry about issues with a custom template. After compiling the PDF document using the function the final result looks like this: <img src="https://aimundo.rbind.io/blog/2021-05-19-using-bookdown-different-authors-in-a-document/Header_3.JPG" class="img-fluid" alt="h-3"></p>
<p>Which is what I wanted. Quite a journey to have this resolved, but I learned a bunch of stuff along the way! I hope this post helps anyone going through the same issues.</p>
<p>A couple of final thoughts:</p>
<ul>
<li><img src="https://latex.codecogs.com/png.latex?LaTeX"> is challenging but there’s whole world of things to experiment with!</li>
<li>YAML headers are temperamental. Sometimes it’s good to use a <a href="https://yamlvalidator.com/"><strong>YAML validator</strong></a> to check it everything works. With more and more options and custom things in it, there is more chance that an indentation is not right and you can spend hours trying to find the problem (trust me, I’ve been there)</li>
<li>Also, I am a convert. Only <code>Bookdown</code> to write documents from now on!</li>
</ul>
<script src="https://cdn.jsdelivr.net/npm/p5@1.4.0/lib/p5.js"></script>
<pre><code>&lt;script src="penrose.js"&gt;&lt;/script&gt;</code></pre>


</section>

 ]]></description>
  <category>R</category>
  <category>tutorial</category>
  <guid>https://aimundo.rbind.io/blog/2021-05-19-using-bookdown-different-authors-in-a-document/</guid>
  <pubDate>Wed, 19 May 2021 00:00:00 GMT</pubDate>
</item>
</channel>
</rss>
