Week 6 - How to create better scripts

CHU0387 | National Taiwan Normal University

Overview

This week, we will have a tutorial on how to prepare your computer for further analyses.

Create beautiful scripts that you can share:

  • Reflections: Why creating scripts that are more suitable to share?
  • Advanced scripts: How to use Markdown documents to share better scripts?

A brief summary of the essential elements:

No new codes this week. We will be using the same dataset as last week.


Please complete the following tasks before our next meeting:

  • Transform your R script from last week into an R Markdown document, and knit it to a PDF file.
  • Try to include Chinese characters, and debug such that they appear in the PDF document.


📊 Better and reproducible scripts with R Markdown

Standard R Scripts only save your code. R Markdown files are an incredible upgrade. They allow you to combine your titles, your narrative text, your R code, and your generated plots into one single, shareable document (like a PDF, Word, or HTML file). This is the gold standard for Open Science!

  • To start, click “New File” > “R Markdown…”

  • RStudio will prompt you for a Title and Author. Once created, you will see a document with a YAML Header at the top between dashed lines ---. This header controls the settings for your final document.

Writing text and code

  • In an R Markdown file, anything you type normally becomes standard text. To actually write R code, you must insert a Code Chunk. Click the “Insert” button at the top of the script and select “R”. A grey box will appear.

The symbol {r} indicates that the code in the grey area is in R language. Hashtags # symbols followed by the | bar indicate settings for the block. Otherwise, they are just comments in R as usual.

  • You can run these individual chunks using the green Play Button in the corner of the grey box.

The “Knit” button

When your document is complete, click the Knit button at the top of the interface. You can choose to create an HTML or even a PDF document! R will automatically run all your code chunks, generate the graphs, format your text beautifully, and produce a polished final document you can share with the world!

📝 In-class exercise

Task list:


📝 Assignment for next week
  • Transform your R script from last week into an R Markdown document, and knit it to a PDF file.
  • Try to include Chinese characters, and debug such that they appear in the PDF document.