1 R-Projects

An R-project stores everything to do with each lab in one place on your computer.

This is incredibly useful - it means that if you switch from R-Cloud, to the lab computers, to your laptop, all you have to do is to move the folder and everything will just work. It also means you have to worry less about directory names.



1.1 Projects using R-Studio Desktop

1.1.1 Creating a new project


  1. If it’s not already open, open R-Studio
  2. Go to the File menu at the very top and click New Project.
  3. Select New Directory, then New Project.
  4. Name your project after your lab .
  5. Under “create project as a subdirectory of”, hit the browse button and go inside your GEOG-364 main folder (you just need to be in the folder, you don’t need to have selected anything). Press open.
  6. Finally, press Create Project,


1.1.2 How do I know it’s worked?

R will change slightly.
- If you look at the top of the screen in the title bar, it should say Lab1-Project R Studio.
- The Files tab should have gone to your project folder. Essentially, R-Studio is now “looking” inside your Lab 1 folder, making it easier to find your data and output your results.

1.1.3 Returning to your lab project

  1. On your computer, find your GEOG-364 folder and go to the lab you want.
  2. Double click on the file with the extension .RProj.


1.2 Projects using Posit Cloud

1.2.1 Creating a new project

  1. Visit the Posit Cloud Login Page:

  1. Create a New Project:

    • Click the button on the top right and select “R-studio project.”

    • A new R-studio Cloud instance will open. Rename it to match your lab.

1.2.2 Returning to your project




2 Packages

2.0.1 How to download/install packages

Just as you don’t need to go to the app store every time you use your weather app, you only need to download and install packages once. There are two methods

  1. Clicking the INSTALL button in the Packages tab, then start typing the package name and it will show up (check the include dependencies box).
  2. In the console, run the install.packages() command with quotes around the package name e.g. install.packages("bardr").

Try installing the bardr package onto your computer


2.0.2 How to load packages you want to use

Installing a package doesn’t make it available to you. For that you need to load it (like clicking on an app). This can be done with the library() command.

In the console type this to install the full works of Shakespeare in the bardr package (https://www.rdocumentation.org/packages/bardr/versions/0.0.9)

library(bardr)

2.0.2.1 What should happen?

If you have managed to install a package successfully, often nothing happens - this is great! It means it loaded the package without errors.

Otherwise, I suggest running this command TWICE! This is because loading packages will print “friendly messages” or “welcome text” the first time you load them.

For example, this is what shows up when you install the tidyverse package. The welcome text is indicating the sub-packages that tidyverse downloaded and also that some commands now have a different meaning.

Tidyverse install messages

Tidyverse install messages

To find out if what you are seeing is a friendly message or an error, run the command again. If you run it a second time and there is no error then nothing should happen.

2.0.3 How to force the computer to use a specific command/packages

You can also use any command from any package by naming it and using ::

For example, this command forces the computer to use the dplyr package version of filter.

dplyr::filter(mydata)



3 R-Markdown Basics

R Markdown is a powerful tool that allows you to combine text, code, and outputs in a single document. This tutorial will guide you through creating an R Markdown document, using templates, understanding its components, and working with key features like visual mode, code chunks, and knitting.

There are also many more hints and tips here https://posit.co/blog/r-markdown-tips-tricks-1-rstudio-ide/.

3.1 Introduction

3.1.1 What is R-Markdown?

Read more here: https://rmarkdown.rstudio.com

Typing commands into the console is like making a phone call to the computer—you communicate but don’t keep a record of your interactions. To save your commands for future use, we use scripts and documents. There are several types:

  • A basic script (.R file): A blank notepad where you save code commands. When you “run” the script, R simply copies and pastes the commands into the console.

  • An R Notebook or R Markdown document (.Rmd file): An interactive document where you can combine text, code, and output in one place. With a single click, you can convert .Rmd files into reports, websites, blogs, presentations, or interactive applications.

R Markdown is especially useful for labs because it allows you to integrate code, output, and written analysis seamlessly. Instead of taking screenshots, you can embed results directly in your document.



3.1.2 R-Markdown Structure

Your markdown file contains three main areas:

  • The YAML code at the top describes what the final output should look like.

    • For example this might be a website, a pdf, a presentation or one of these 21 other formats…https://rmarkdown.rstudio.com/lesson-9.html

    • It also includes other ‘meta-data’ for example the title/author name, whether you want a table of contents and any themes. For example, in the screenshot above, I included:

      • The title
      • The author (note,use your email ID not your name)
      • Automatically created today’s date
      • A floating table of contents
      • Numbered sections (this won’t appear until you start typing section headings)
      • The lumen theme.
    • See “Editing YAML” below for more information.

  • The report text.

    • This is essentially the same as Microsoft word, where you can write up interpretations, include pictures, tables, links and equations.. See “Editing text” below for more information.
  • Code chunks

    • These are spaces for you to R-Code. They are essentially “mini consoles”. To run the code inside, click the little green arrow on the right. This copies the code into the console, runs it, then copies the output underneath the code chunk, integrating it into your report. See “Editing R-Markdown” below for more information.


3.2 Creating Markdown Files

3.2.1 Creating a basic R-Markdown document


To create a new R Markdown document

  1. Go to FileNew FileR Markdown...
  2. Choose a document type (HTML, PDF, or Word). For now, | select HTML.
  3. Give your document a title and specify the author as | your Email ID e.g. hlg5155
  4. Click OK
  5. If this is your first time ever doing this or you’re running a new POSIT-Cloud project, then R-studio might ask to download some packages before it can do this this. Say yes.
  6. A new file should appear on your screen. At the top of that window (by the knit button, there is a save button. Save it as something relevant INSIDE YOUR PROJECT FOLDER!

RStudio will generate a default R Markdown file with an example of formatted text and an embedded code chunk.


3.2.1.1 Further editing the YAML code

There are many different options you can add to a basic RmD file, by changing the YAML code at the top. For example you can add a table of contents, make the auto-hide (code folding) or change the theme.

Click here to see examples of how to do this: https://psu-spatial.github.io/Stat462-2025/CH2_EACHLAB.html#34_Editing_YAML


3.2.1.2 Important

  • Before you continue, on your computer (outside R-Studio), go to your project folder

  • MAKE SURE THE RMD FILE SAVED IN YOUR PROJECT FOLDER. Also, check you didn’t accidentally create a load of sub-folders inside your lab. If so, delete/move things around until it looks like this.




3.2.2 Using a custom R template from a package

There are also now several package which contain professional markdown templates. Common examples include

To use one of these packages:

  1. Make sure the relevant package is installed (e.g. packages tab, install button)

  2. Go to FileNew FileR Markdown...

  3. Click the Templates button

  4. Select the template you want to use.

  5. Click OK.

  6. A new file should appear on your screen. At the top of that window (by the knit button, there is a save button. Save it as something relevant INSIDE YOUR PROJECT FOLDER!

Alternatively, you can replace your YAML code with the suggested code from that theme.


3.2.2.1 Further editing the YAML code

There are many different options you can add to a basic RmD file, by changing the YAML code at the top. For example you can add a table of contents, make the auto-hide (code folding) or change the theme.

The easiest way to see what is available for your particular theme is to go to the package website and take a look at the documentation (scroll down). For example

You can also just try and edit the YAML code, press knit and see if it works. Click here to see examples of how to do this: https://psu-spatial.github.io/Stat462-2025/CH2_EACHLAB.html#34_Editing_YAML

NOTE, PrettyDocs does NOT allow a floating table of contents.


3.2.2.2 Important!

Sometimes rmdformats makes an extra subfolder and puts your report in there.

  • So before you continue, on your computer (outside R-Studio), go to your project folder

  • MAKE SURE THE RMD FILE SAVED IN YOUR PROJECT FOLDER. Also, check you didn’t accidentally create a load of sub-folders inside your lab. If so, delete/move things around until it looks like this.




3.2.3 Using ChatGPT for custom templates

Finally, we can now use ChatGPT to help make custom YAML code for whatever template you want or to help you fix broken themes/YAML code. It will almost certainly take interations - and look at github or google cool markdown formats for examples.

For example,





3.3 Editing YAML

3.3.1 Basics

R-Markdown is especially powerful because it is easy to convert your reports into many different templates. We do this via changing the YAML code at the top. Luckily, you do not have to remember all the YAML commands yourself.

The basic RmD format is pretty boring. So if you go this route, it’s good to edit the YAML code to add in a few additional features. Here is some example YAML code that I often use as a baseline. CAREFULLY replace yours with this, paying attention to spacing.

---
title: "change to add your title"
author: "hlg5155 or your email ID"
date: "`r Sys.Date()`"
output: 
  html_document:
    number_sections: true
    toc: true
    toc_float: true
    toc_depth: 3
    theme: journal
---  

There are many more details about different options on these websites:

3.3.2 Themes

There are about 10 built-in themes in R to quickly change the format of your documents. You view them here, alongside ways to further customize your document (for example to add a table of contents)

If you used a custom theme from rmdformats, check out their websites to see if there are additional options you wish to add in.

3.3.2.1 Custom R-Markdown Templates

As I described in the previous section, you can also use other themes from packages like rmdformats, but rather than just changing the word “theme”, the entire YAML changes.

So the easiest way to do this is to create a blank new file for the template you want, then copy/paste the entire YAML code across to your report.



3.4 Editing markdown text

3.4.1 Visual vs source mode

RStudio’s standard output is “source mode” where you see your text in a raw format.

RStudio now provides a Visual Editor to simplify text formatting. When switched on, you see something similar to the final output format and get access to all the normal word processing buttons (e.g. bold/headings etc.). To switch between the two modes:

  1. Click the Visual tab in the .Rmd editor.

  2. Use the toolbar to format text, add links, or insert images.

  3. Switch back to Source mode to view the underlying Markdown format.

Visual mode is incredibly useful, because you don’t need to remember any of the keyboard commands for formatting text. But… it can be a pain when editing/deleting code-chunks. To do that, I often switch back to source mode.

3.4.2 Pictures and tables

These are easy to add using visual mode. Just go to the text-editing menu at the top of the report.

3.4.3 Headings

Please use these! They allow your table of contents to be created correctly which allows easy navigation in your reports. For example, Heading 1 = Chapter Title, Heading 2 = sub-title etc.

In visual mode, click on the line you want then look at the text formatting menu. Click the arrow by “normal” and change to the heading you want.

3.4.4 Mathematical equations

THESE GO INTO THE TEXT SECTION! NOT INTO A CODE CHUNK.

Although I have heard rumors you can copy/paste equations into R, the easiest way I have found is to:

  1. First, get the equation you want in chatgpt or similar and ask it to output as LateX format

  2. Type $$ to tell R you are adding an equation, then paste the equation in a line of its own.

e.g. If you type this into the TEXT (not a code chunk)


$$
E_n = -\frac{m e^4}{2 \hbar^2} \frac{1}{n^2}
$$

In visual mode, you should see get

\[ E_n = -\frac{m e^4}{2 \hbar^2} \frac{1}{n^2} \]

If you want an equation on the same line, use single $ signs. E.g typing this into the TEXT


Hello! Here is an inline equation: $e^4$, that you can include mid-sentence

Will give you

Hello! Here is an inline equation: \(e^4\), that you can include mid-sentence.



3.5 Editing code

3.5.1 Adding new code chunks

In visual mode, you can add code chunks by clicking on the little green button at the top right and choosing R.

In source mode, you can add a code chunk by typing this

Where the little symbols before the {R} are called BACK-TICKS. I often just copy/replace.


3.5.2 Running code chunks

There are several ways you can run the code in a code chunk. The easiest is to use the controls on each chunk.

  • To run that chunk → Click the green “Play” (▶) button in the top-right corner of the chunk.

  • To Run all chunks above → Click the small downwards arrow with line under it just to the left of the Play button.

Or via the Run menu on the top right.

3.5.3 Code Chunk Options

3.5.3.1 What are they?

Code chunk options control how your code behaves when you knit the document. You can suppress messages, hide warnings, or customize the appearance of your output. Here are some common options you might use:

  • message = TRUE/FALSE — Show or hide R messages when knitting.
  • warning = TRUE/FALSE — Show or hide warnings. Errors will still be displayed.
  • include = TRUE/FALSE — Show or hide both the code and its output.
  • echo = TRUE/FALSE — Show or hide the code but still display its output.
  • eval = TRUE/FALSE — Show the code, but don’t actually run it. Useful if you can’t make it work, but want to still knit and submit.

3.5.3.2 Editing Options in Source Mode

  • Each code chunk starts and ends with three backticks. The {r inside the curly braces indicates it’s R code.
  • After {r, you can add options to modify the behavior of the code when knitting. For example, use message=FALSE and warning=FALSE to suppress library loading messages and warnings.


3.5.3.3 Editing Options in View Mode

In View mode, click the small cogwheel next to the run triangle at the top of the code chunk to set these options without remembering commands.


3.5.3.4 Setting Default Options for the Whole Document

To apply settings to all code chunks, place this code chunk at the top of your document (below the YAML):

```{}
knitr::opts_chunk$set(echo=TRUE, 
                      warning=FALSE, 
                      message=FALSE)
```

Many templates include default settings, but you can easily customize them to fit your needs.



3.6 Knitting

3.6.1 Kniting your files

The file on your screen isn’t the finished article. To see how it will look as a final version, we need to “knit” it.

Knitting an R Markdown document means converting it into a final output format (such as HTML, PDF, or Word). When you knit a document, RStudio executes the code chunks, formats the Markdown text, and generates a nicely formatted report.

Go to the top of the .Rmd file, find the knit button. Press it (you might have to first save your script if you haven’t already, then press it again). This will only work if you have all the commands saved in your lab-script e.g. if you read in the data but didn’t write the command into your report, it will crash.

3.6.1.1 IF YOU GET A KNITTING ERROR

The terminal text will update you as your report turns into a website. If you get an error, then the exact line number with the problem and a description of the error will be printed on the console. For example, here I tried to print out a variable that didn’t exist.