Working with R and RStudio

BIOSCI 504 · Day 2

Denis O’Meally

City of Hope

By the end

You should be able to:

  1. distinguish R from RStudio;
  2. locate where code, results, objects, files and help appear;
  3. recognize common R values, vectors and tibble structure;
  4. use an R Project and a Quarto document to leave work that runs again.

R and RStudio are different

R

  • a programming language
  • software that executes R code
  • available with or without RStudio

RStudio

  • an integrated development environment
  • an editor and interface for working with R
  • also works with files, plots, help and projects

R answers the command you gave it

R evaluates code literally.

  • A malformed command may produce an error.
  • A questionable operation may produce a warning.
  • A valid command may produce an answer to the wrong question.

Note

Code that runs is not evidence that the intended analysis was performed.

The RStudio workspace

RStudio showing the Source pane at upper left, Environment at upper right, Console at lower left, and Files, Plots, Help and Viewer at lower right.

Where would you edit code, see an answer, inspect an object and open help?

Four panes, four jobs

Pane Main job
Source Edit and preserve scripts and Quarto documents
Console Execute code and show immediate responses
Environment / History Inspect objects in the current session and recent commands
Files / Plots / Help / Viewer Navigate files and inspect results or documentation

The arrangement can change. The jobs do not.

In RStudio now

Find these four places in your own window:

  1. Source
  2. Console
  3. Environment
  4. Files and Help

Then return your attention to the front.

A Project gives the analysis a root

BIOSCI504/
├── BIOSCI504.Rproj
├── _quarto.yml
├── README.md
└── exercises/

Open BIOSCI504.Rproj before beginning course work.

Create the course Project once

If you have not already created it:

BIOSCI504::create_course_project("~/BIOSCI504")

Then open BIOSCI504.Rproj in RStudio.

Important

Creating the .Rproj file does not open it for you.

Add the Lecture 2 code-along

From inside the course Project:

BIOSCI504::copy_template("lecture-2")

Open:

exercises/working-with-r/analysis.qmd

Relative paths describe relationships

Machine-specific:

C:/Users/Alex/Documents/BIOSCI504/exercises/working-with-r/analysis.qmd

Relative to the Project:

exercises/working-with-r/analysis.qmd

Which path can survive a different username or computer?

Inputs, instructions and products

Keep unchanged Preserve and edit Regenerate
raw observations scripts and .qmd files figures
metadata analytical decisions tables
data dictionaries explanations rendered HTML

Generated output should be traceable to recorded instructions.

The Environment is temporary

The course Project sets:

RestoreWorkspace: No
SaveWorkspace: No

Restarting R clears session objects. It does not remove saved files.

Console and document

Console

> 2 + 2
[1] 4

Immediate interaction with R.

Quarto document

# saved inside an R code chunk
2 + 2

An executable record.

The Console is a REPL

Read → evaluate → print → loop

> 2 + 2
[1] 4
>
  • > is ready for an expression.
  • [1] marks the first displayed element.
  • The next > begins the loop again.

Common atomic storage types

Expression Type Meaning here
18.2 double numerical measurement
18L integer whole number marked with L
"M01" character quoted text
TRUE logical true or false

Check with typeof().

Missing values retain a type

Expression typeof() Meaning
NA logical missing value, default type
NA_integer_ integer missing integer
NA_real_ double missing measurement
NA_character_ character missing text
is.na(c("M01", NA_character_, "NA"))
# FALSE  TRUE FALSE

NA_character_ is missing. "NA" is text.

Atomic vectors hold one underlying type

weights_g <- c(18.2, 19.5, 20.1)
typeof(weights_g)
length(weights_g)
mean(weights_g)
  1. c() combines values into a vector.
  2. <- assigns that vector to weights_g.
  3. length() and mean() receive the vector as an argument.

Predict the result before running the chunk.

A tibble contains column vectors

measurements <- tibble(
  mouse_id = c("M01", "M02", "M03"),
  weight_g = weights_g
)

glimpse(measurements)
typeof(measurements)
class(measurements)
Rows: 3
Columns: 2
$ mouse_id <chr> "M01", "M02", "M03"
$ weight_g <dbl> 18.2, 19.5, 20.1

Each column is a vector. All columns have the same length.

Missing, undefined, infinite or absent?

Value Description Detect with
NA unknown or missing value is.na()
NaN undefined numerical result is.nan()
Inf, -Inf infinite numerical result is.infinite()
NULL absence; length zero is.null()

is.finite() is false for NA, NaN and both infinities.

Removing a missing value changes the calculation

weights_with_missing <- c(18.2, NA_real_, 20.1)

mean(weights_with_missing)
# [1] NA

mean(weights_with_missing, na.rm = TRUE)
# [1] 19.15

How many observations contribute to the second mean?

Packages and help

library(tidyverse)
?mean
  • library() attaches an installed package for the current session.
  • ?mean opens the help page for mean().
  • Help records arguments, returned values and examples.

Read the response before editing

mean(weight_g)
Error: object 'weight_g' not found

Compare:

weights_g
measurements$weight_g

One value can change a vector’s type

mixed_weights <- c(18.2, 19.5, "20.1")
typeof(mixed_weights)
mean(mixed_weights)
[1] "character"
[1] NA
Warning message:
In mean.default(mixed_weights) :
  argument is not numeric or logical: returning NA

The code ran. Is its output usable?

Error, warning, output

Response What it establishes
Error The requested operation did not complete
Warning The operation completed, but a condition needs attention
Output The code ran and returned something

None establishes that the scientific question and analysis match.

Restart and render

  1. Save analysis.qmd.
  2. Select Session > Restart R.
  3. Confirm that the Environment is empty.
  4. Select Render.

If it renders, the document contains the code needed to reconstruct its output.

Working method for this course

  1. State the question and prediction.
  2. Specify what the analysis should do.
  3. Write or generate a small section of code.
  4. Run it and inspect the result.
  5. Preserve the working step in the document.
  6. Restart, render and verify before interpreting.

AI interfaces can sit closer to the analysis

Interface Context supplied to the model
Teams Copilot text, code and errors that you paste into chat
gander / chattr selected editor content or RStudio context
ellmer context assembled programmatically in R
coding agents project files, terminal commands and tool results

Closer integration changes what context can be supplied and where the result appears. It does not decide whether the analysis is scientifically appropriate.

For any interface, ask:

  1. What can it see?
  2. Which service receives the data?
  3. How will the returned code be checked?

gander edits the document in front of you

Two RStudio screenshots from the gander documentation. In the first, a selected object and a short request are supplied to the addin. In the second, inserted ggplot2 code is selected and its plot is visible.

Select context → describe a change → inspect inserted code → run or revise

Chat beside the analysis—or call the model from R

chattr

RStudio with a chattr conversation open in the Viewer pane. The response contains R code and controls for copying it.

Viewer chat with analysis context; preview the request and move returned code into the document.

ellmer

chat <- ellmer::chat_ollama()

chat$chat(
  "Explain this warning in one sentence"
)

R constructs the conversation and receives the result. It can also request structured values or register tools.

Next: what does the table represent?

You now have:

  • a Project that locates the work;
  • a Quarto document that records it;
  • a clean-render test that checks whether it can run again.

Next we examine what the rows, columns and measurements mean.

Questions

Then take a short break.

Further reading

Portions adapted from Data Analysis and Visualization in R for Ecologists, The Carpentries, CC BY 4.0. Adapted for BIOSCI 504; no endorsement is implied.