Skip to content

Commit

Permalink
Create how-to-code chapter
Browse files Browse the repository at this point in the history
This commit creates a chapter on how to show code.
  • Loading branch information
Reza Hakimazar committed Sep 25, 2024
1 parent 034e429 commit d8dab33
Showing 1 changed file with 197 additions and 0 deletions.
197 changes: 197 additions & 0 deletions chapters/how-to-code.qmd
Original file line number Diff line number Diff line change
@@ -0,0 +1,197 @@
# How to show code in Quarto?

Showing code in Quarto falls under the category of text formatting at its most basic level, but Quarto brings more to the table than just showing plain code. Quarto can help with code execution, showing graphs, interact with the code and more!

## Formatting the Text

It is simple to add code in Quarto. First, specify that you are writing code using three `backticks` (\`\`\`). Then, define the programming language inside curly brackets. For instance, if you are using R, write `{r}`. Then, write the code. Finally, close the chunk using three more backticks (\`\`\`). This is how the output should look like:

```{r}
# This piece of text works as a comment in R.
# Since we have specified our language, from here on, you can write codes in R language.
# create variables
v1 <- 3
v2 <- 4
# multiply the variables
m <- v1 * v2
# DON'T FORGET TO CLOSE THE CHUNK USING THREE MORE BACKTICKS (```)
```

Each programming language has its unique identifier in Quarto. The table below shows how to use different programming languages in Quarto.

| Programming Language | Quarto Identifier |
|----------------------|-------------------|
| R | {r} |
| Python | {python} |
| Julia | {julia} |
| Bash | {bash} |

## Code Annotations

Imagine you want to present the analysis of a complicated dataset. For the audience the chunks in your analysis speak their own secret language! Therefore, some clarification would help them to understand it better. In such situations, code annotation comes in handy.

Two steps should be followed to annotate the code in Quarto.

1. First, we comment the code (as in R, `#` is used to comment texts) and assign it a number inside angle brackets `# <1>`. Make sure to include a space between `#` and `<`.

2. Second, write your annotations directly after the chunk of code, using the assigned number for reference. The annotations must be outside the chunk of code, which means anything written as annotation, must be written after the three backticks ```` (```) ````.

This is how the output looks like without code execution:

```{{r}}
model <- lm(ProductivityScore ~ StressLevel + SleepQuality + Age + Gender, data = data) # <1>
```

1. Performs regression analysis

This is how the output looks like with code execution:

```{r}
# create a dataframe
team <- c("a", "b", "c") # <1>
profit <- c(45, 63, 47) # <2>
df <- data.frame(team, profit)
print(df) # <3>
```

1. create a vector for `teams`
2. create a vector for `profit`
3. prints `df`

## Escaping from Code Execution

When presenting the code for educational purposes, as we do here, sometimes code execution is not necessary. In fact, it might disrupt the code presentation. Quarto allows us to prevent codes from execution by using `{{}}` instead of `{}` at the start of the code chunk. This way, only the code and its annotations are displayed without being executed.

```{{r}}
# create variables # <1>
v1 <- 3
v2 <- 4 # <1>
# multiply the variables # <1>
m <- v1 * v2 # <1>
# DON'T FORGET TO CLOSE THE CHUNK USING THREE MORE BACKTICKS (```)
```

1. This chunk of code is presented without execution

## Echo, Warning, and Code Fold

Quarto has several features for showing code in a more organized way.

### Echo

It is possible to customize whether we want to show the code in the output. When writing a report, it is probably redundant to include the code in the final draft. However, the code is necessary for the analysis and the results written in the report. In this scenario, `echo` helps! By writing `#| echo: false` at the start of a code chunk, no code will be exported to the output document. If we use `#| echo: false` for the last chunk of code, the final output will only be the dataframe.

```{r}
#| echo: false
print(df)
```

`#| echo: false` prevents showing the executed code and only let's the result to be displayed.

### Warning

Another output option in Quarto in `#| warning`. As you can tell from its name, this command manages the warnings in code execution. `#| warning: false` prevents the warnings to show in the output. This is how a code will look like *without* `#| warning: false`.

```{r}
#| warning: true
# Creating a numeric vector
numbers <- c(1, 2, 3, "four", 5)
# Attempting to calculate the mean (warning: "four" will be coerced)
mean(numbers)
```

This is how a code will look like *with* `#| warning: false`.

```{r}
#| warning: false
# Creating a numeric vector
numbers <- c(1, 2, 3, "four", 5)
# Attempting to calculate the mean (warning: "four" will be coerced)
mean(numbers)
```

### Code Fold

Sometimes the code is lengthy and uses up space to show it fully in the document. To organize such huge chunks of code, `#| code-fold`. `code-fold` can either be set on `true`, `false` or `show`. The best way to understand this feature is through an example.

```{r}
#| code-fold: true
#| warning: false
# Load necessary libraries
library(ggplot2)
library(dplyr)
# Create a sample dataset
set.seed(123)
data <- data.frame(
ID = 1:100,
Age = rnorm(100, mean = 30, sd = 10),
Income = rnorm(100, mean = 50000, sd = 15000),
Group = sample(c("Control", "Treatment"), 100, replace = TRUE),
Score = rnorm(100, mean = 50, sd = 10)
)
# Add some noise and interaction to the data for complexity
data <- data %>%
mutate(Score = ifelse(Group == "Treatment", Score + 5, Score),
Income = ifelse(Age > 35, Income + 2000, Income))
# Build a linear model to predict Score based on Age, Income, and Group
model <- lm(Score ~ Age + Income + Group, data = data)
# Predict scores based on the model
data$Predicted_Score <- predict(model, newdata = data)
# Create a ggplot to visualize the relationship between Age, Income, and Score
ggplot(data, aes(x = Age, y = Score, color = Group)) +
geom_point(aes(size = Income), alpha = 0.7) + # Scatter plot with Income as size
geom_smooth(method = "lm", se = FALSE) + # Add a linear regression line
labs(title = "Score by Age and Income",
x = "Age",
y = "Score",
color = "Group",
size = "Income") +
theme_minimal()
```

#### Code Summary

The prompt used to display the code can be customized. Here, we set the `#| code-fold` on `show` and `code-summary` is shown as "Click to hide/show the code!". `#| code-fold = show`, initially displays the code.

```{r}
#| code-fold: show
#| code-summary: "Click to hide/show the code!"
# Plot residuals to check the fit of the model
par(mfrow = c(2, 2))
plot(model)
```

## Referencing Code from External Sources

Quarto enables calling a script file from a local directory (`source`), evaluate it (`eval`), and then present the output without embedding the whole code in the Quarto document. First, the script should be evaluated using `#| eval: true`. If `#| eval = false` Quarto just shows the script and skips code execution. Then, `source ("file path")` loads the local script to use it in the Quarto document.

As an example, we use a pre-installed R dataset about iris flowers (Iris setosa, Iris versicolor, and Iris virginica) called `iris`. There is a script file that performs an analysis on this dataset and draws a graph. Let's use `source` and `#| eval = true`!

```{r}
#| echo: true
#| warning: false
#| eval: true
# Source the external R script
source("E:\\FAIR-Teaching\\Git-Repository\\quarto-book\\chapters\\script.R")
```

## Data in a Downloadable Folder

0 comments on commit d8dab33

Please sign in to comment.