FAQ: How to format your code

Formatting Code: the Basics

All code or console output you include in your posts should be formatted properly. Luckily, this is very easy to do! Just use the code formatting button at the top of the post editing box:

  1. Select some code

  2. Click the </> button!

The code formatting button automatically adds special Markdown formatting symbols to whatever you selected. If you check the preview pane to the right of your post, you'll see that the forum software now outputs nicely formatted code :sparkles::grinning:.

The code formatting button is pretty smart! It can tell the difference between snippets of code that are part of a sentence and blocks of code that stand alone. Sometimes the software will even detect that you are pasting in code and add the formatting symbols automatically! :mage:

Why should I format code and console output?

There are plenty of good reasons to learn how to properly format your code!

  1. Keeping things tidy is one of our core community principles :sweep:
  2. Unformatted code is difficult for other people to read :dizzy_face:
    • Leaving your code unformatted makes it less likely you'll get replies :disappointed:.
    • Continuing to post unformatted code after someone has asked you to fix it often comes across as rude :flushed:.
  3. Console output often contains characters that the forum software interprets as special formatting symbols (e.g., #, $ or < and >). This can cause parts of the text to become unrecognizable, or even to disappear completely! :anguished: Marking console output as code keeps it safe from confusing accidental formatting.

Can't I just post a screenshot?

Please don't post screenshots of code. Screenshots of code are even worse than unformatted code :confounded:. Here's why:

  • Screenshots are often difficult to read (and useless to anybody using a screen reader).
  • Helpers usually want to try to run your code, not just read it. Screenshots force your helpers to type everything back in by hand :weary:. That's a lot to ask and many people won't bother.
  • Screenshots aren't searchable, so they don't help others with similar problems find your post later on.

Formatting Code: Beyond the Basics

How do I format R Markdown source?

Use four backticks and the "markdown" syntax hint to surround the source of R Markdown documents:

Type this: See this:
````markdown
---
title: "It's full of cars!"
output: html_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```

## R Markdown

This is an R Markdown document. 
Markdown is a simple formatting 
syntax for authoring HTML, PDF, 
and MS Word documents.

```{r cars}
summary(cars)
```
````
---
title: "It's full of cars!"
output: html_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```

## R Markdown

This is an R Markdown document. 
Markdown is a simple formatting 
syntax for authoring HTML, PDF,
and MS Word documents. 

```{r cars}
summary(cars)
```

What is this "backtick" symbol?

The backtick symbol looks like this:

`

It is not the same thing as a single quote. It is technically the grave accent symbol, but used alone and not combined with any letter.

On QWERTY keyboards, the backtick is found on the same key as the tilde (~), immediately to the left of the 1 key:

Adapted from: Denelson83, CC BY-SA 3.0

My keyboard doesn't have a backtick!

The backtick is not available on some keyboard layouts, and can be hard to find on others.

In these cases, the easiest thing to do is probably to use the code formatting buttons instead of typing backticks manually. However, you can also click the code formatting button without anything selected to insert backticks into the post editing box. Then copy and paste those backticks wherever you need them!

What are all the ways I can format code by hand?

Code can be formatted by hand in several ways:

  • Use any of the CommonMark markdown code formatting styles: indented code blocks, fenced code blocks, and single-backtick inline code.

    For fenced code blocks, you can supply syntax highlighting hints, similar to Github-flavored Markdown. If you don't supply a hint, the highlighter will guess. The hint for R code is ```r , but on this site the highlighter will usually identify R code correctly without a hint.

  • Use BBCode syntax: [code] and [/code]

  • Use HTML: <code></code> for inline code, and <pre><code></code></pre> for blocks of code.

Type this: See this:
```javascript
var body = d3.select("body");
var div = body.append("div");
div.html("Hello, world!");
```
var body = d3.select("body");
var div = body.append("div");
div.html("Hello, world!");
[code]
var body = d3.select("body");
var div = body.append("div");
div.html("Hello, world!");
[/code]
var body = d3.select("body");
var div = body.append("div");
div.html("Hello, world!");
<pre><code>
var body = d3.select("body");
var div = body.append("div");
div.html("Hello, world!");
</code></pre>
var body = d3.select("body");
var div = body.append("div");
div.html("Hello, world!");

:memo: Version 1.0.0

Got something to ask? Or add?

FAQ posts are closed to replies. If you have any questions or suggestions, please visit the corresponding discussion thread: https://community.rstudio.com/t/faq-discussion-how-to-format-your-code/37220

6 Likes
Add a Zoom on my plot
FAQ: What's a reproducible example (`reprex`) and how do I do one?
Can I put the result of read.files in a list and iterate through the list to match specific files
Displaying information on click in timevis.r
Track down error in R
Using www folder: Save and display pdf
Problem with Histogram
Ggplot adding points in large dataset, looks terrible
Cannot export a raster image after using the random forest classification
Error: cannot find function trim
Checking is.null in a case_when statement
How to customise colours to specific things
How to average/mean variables in R based on the level of another variable (and save this as a new variable)?
Problem in 'matplot' function
How to save SAS data into RData format
Ggplot troubleshoot: Error: Aesthetics must be either length 1 or the same as the data (24): x, y, fill
Create Volcano Plot
Error in file.choose() file choice cancelled
Error Preventing Knitting
Error in gzfile(path.expand(tarfile), "rb") : cannot open the connection In addition: Warning message: In gzfile(path.expand(tarfile), "rb") : cannot open compressed file 'NA', probable reason 'Permission denied'
Curl error 18 occurred
Multi-column-type Summarise
Error during deploy shiny app
Graph with errobar using percentile function
Suddelny, base solve function does not work on RStudio
Problem with source_python using pulp in Windows
Maptile fetched in RStudio Desktop but not RStudio Server
How to give admininstrative rights while running R script from terminal in Linux?
If/Else logic for fixing ZipCodes
Document term matrix in XGBoost classifier
Create plots using multpile dataframes
How to Ignore one of the factors in a Column
How to upgrade a package when using packrat
Error sourcing while creating Shiny app
R : dynamic plot value and x axis value for line chart
How to create a legend for ggplot
System call within R shiny
Not able to get an image into word/pdf from URL in RMarkdown
Shiny app r Programming
How to create a legend for ggplot
Efficient way to get column names.
I used clean data according a column number range isn't work correct.
Changing Base R code to dplyr/sparklyr
Package ‘dplyr’ is not available (for R version 3.4.3)
Shiny dashboard
Data frame not inserted the right value.
How to remove for
Error reading file
cut plots in the plot window
Making a bar plot
web scrapping data from webpage and save in data frame
Ggplot legend error
Text concatenation
outside save from loop
Using a pipe to sequentially filter data - receiving error
Fibbonacci series and Golden Ratio
Linear Mixed Model
Need help with strange pop-ups
Linear regression line looks wrong
Chapter starts with 0.1 (not 1.0) in pdf_book format
R Studio crashes when connecting to Spark with sparklyr
Error when trying to use corrplot
Problems with loading ggplot2
Pregunta Frecuente: ¿Cómo dar formato a su código?
Get google place details for multiple place ids
FAQ Discussion: How to format your code
Aggregate data set by year (year is the column name and the years are in the rows of the table)
Help on Looping
How I can convert symbols to color code in this shiny code
What did my colleague do to prepare the data for an ICC?
Doubt with loops
Fatal Error when running Keras/Tensorflow with GPU
Plot multiple line graph over time
“edit” and “read.table” on R for Mac
Show matched and unmatched results from vector in data table
Improve the speed
Connecting To A SQL Server
Sparklyr 's error
Help with function convert.inp in RMark