<h1><spanid="sec-workflow-style"class="quarto-section-identifier d-none d-lg-block"><spanclass="chapter-title">Workflow: code style</span></span></h1><p>Good coding style is like correct punctuation: you can manage without it, butitsuremakesthingseasiertoread. Even as a very new programmer it’s a good idea to work on your code style. Using a consistent style makes it easier for others (including future-you!) to read your work, and is particularly important if you need to get help from someone else. This chapter will introduce to the most important points of the <ahref="https://style.tidyverse.org">tidyverse style guide</a>, which is used throughout this book.</p><p>Styling your code will feel a bit tedious to start with, but if you practice it, it will soon become second nature. Additionally, there are some great tools to quickly restyle existing code, like the <ahref="https://styler.r-lib.org">styler</a> package by Lorenz Walthert. Once you’ve installed it with <code>install.packages("styler")</code>, an easy way to use it is via RStudio’s <strong>command palette</strong>. The command palette lets you use any build-in RStudio command, as well as many addins provided by packages. Open the palette by pressing Cmd/Ctrl + Shift + P, then type “styler” to see all the shortcuts provided by styler. <ahref="#fig-styler"data-type="xref">#fig-styler</a> shows the results.</p><divclass="cell">
<figureid="fig-styler"><p><imgsrc="screenshots/rstudio-palette.png"alt="A screenshot showing the command palette after typing "styler", showing the four styling tool provided by the package."width="638"/></p>
<figcaption>RStudio’s command palette makes it easy to access every RStudio command using only the keyboard.</figcaption>
<p>We talked briefly about names in <ahref="#sec-whats-in-a-name"data-type="xref">#sec-whats-in-a-name</a>. Remember that variable names (those created by <code><-</code> and those created by <code><ahref="https://dplyr.tidyverse.org/reference/mutate.html">mutate()</a></code>) should use only lowercase letters, numbers, and <code>_</code>. Use <code>_</code> to separate words within a name.</p>
<p>As a general rule of thumb, it’s better to prefer long, descriptive names that are easy to understand, rather than concise names that are fast to type. Short names save relatively little time when writing code (especially since autocomplete will help you finish typing them), but can be time-consuming when you come back to old code and are forced to puzzle out a cryptic abbreviation.</p>
<p>If you have a bunch of names for related things, do your best to be consistent. It’s easy for inconsistencies to arise when you forget a previous convention, so don’t feel bad if you have to go back and rename things. In general, if you have a bunch of variables that are a variation on a theme you’re better off giving them a common prefix, rather than a common suffix, because autocomplete works best on the start of a variable.</p>
</section>
<sectionid="spaces"data-type="sect1">
<h1>
Spaces</h1>
<p>Put spaces on either side of mathematical operators apart from <code>^</code> (i.e., <code>+</code>, <code>-</code>, <code>==</code>, <code><</code>, …), and around the assignment operator (<code><-</code>).</p>
<p>It’s OK to add extra spaces if it improves alignment. For example, if you’re creating multiple variables in <code><ahref="https://dplyr.tidyverse.org/reference/mutate.html">mutate()</a></code>, you might want to add spaces so that all the <code>=</code> line up. This makes it easier to skim the code.</p>
<p><code>|></code> should always have a space before it and should typically be the last thing on a line. This makes it easier to add new steps, rearrange existing steps, modify elements within a step, and to get a 50,000 ft view by skimming the verbs on the left-hand side.</p>
<p>If the function you’re piping into has named arguments (like <code><ahref="https://dplyr.tidyverse.org/reference/mutate.html">mutate()</a></code> or <code><ahref="https://dplyr.tidyverse.org/reference/summarise.html">summarize()</a></code>), put each argument on a new line. If the function doesn’t have named arguments (like <code><ahref="https://dplyr.tidyverse.org/reference/select.html">select()</a></code> or <code><ahref="https://dplyr.tidyverse.org/reference/filter.html">filter()</a></code>) keep everything on one line unless it doesn’t fit, in which case you should put each argument on its own line.</p>
summarize(delay = mean(arr_delay, na.rm = TRUE), n = n())</pre>
</div>
<p>After the first step of the pipeline, indent each line by two spaces. If you’re putting each argument on its own line, indent by an extra two spaces. Make sure <code>)</code> is on its own line, and un-indented to match the horizontal position of the function name.</p>
<p>It’s OK to shirk some of these rules if your pipeline fits easily on one line. But in our collective experience, it’s common for short snippets to grow longer, so you’ll usually save time in the long run by starting with all the vertical space you need.</p>
# While this takes up 4x as many lines, it's easily extended to
# more variables and more steps in the future
df |>
mutate(
y = x + 1
)</pre>
</div>
<p>Finally, be wary of writing very long pipes, say longer than 10-15 lines. Try to break them up into smaller sub-tasks, giving each task an informative name. The names will help cue the reader into what’s happening and makes it easier to check that intermediate results are as expected. Whenever you can give something an informative name, you should give it an informative name. Don’t expect to get it right the first time! This means breaking up long pipelines if there are intermediate states that can get good names.</p>
</section>
<sectionid="ggplot2"data-type="sect1">
<h1>
ggplot2</h1>
<p>The same basic rules that apply to the pipe also apply to ggplot2; just treat <code>+</code> the same way as <code>|></code>.</p>
# Plot data --------------------------------------</pre>
</div>
<p>RStudio provides a keyboard shortcut to create these headers (Cmd/Ctrl + Shift + R), and will display them in the code navigation drop-down at the bottom-left of the editor, as shown in <ahref="#fig-rstudio-sections"data-type="xref">#fig-rstudio-sections</a>.</p>
<figcaption>After adding sectioning comments to your script, you can easily navigate to them using the code navigation tool in the bottom-left of the script editor.</figcaption>
<p>In this chapter, you’ve learn the most important principles of code style. These may feel like a set of arbitrary rules to start with (because they are!) but over time, as you write more code, and share code with more people, you’ll see how important a consistent style is. And don’t forget about the styler package: it’s a great way to quickly improve the quality of poorly styled code.</p>
<p>So far, we’ve worked with datasets bundled inside of R packages. This makes it easier to get some practice on pre-prepared data, but obviously your data won’t available in this way. So in the next chapter, you’re going to learn how load data from disk into your R session using the readr package.</p>