Using RStudio To Write Scripts

ASI: Introduction to R

Author
Affiliation

Dr Stevie Pederson

Black Ochre Data Labs
The Kids Research Institute Australaia

Published

September 2, 2025

The Script Window

RStudio: The Script Window

Best practice for analysis is to enter all code in the Script Window

  • This is a plain text editor \(\implies\) RStudio will:
    • highlight syntax for us
    • help manage indenting
    • enable auto-completion (it can be slower than your typing)
  • Enter code in your script and send it to the R Console
  • We save this file as a record of what we’ve done
    • Code is the important object \(\implies\) can recreate all results

RStudio: The Script Window

  • I sometimes use a double ## for comments at the start of a line
  • Makes it harder to accidentaly uncomment
  • We can write comments by starting a line with the #
    • Anything following this symbol will not be executed
    • Can write notes to ourselves and collaborators
    • We can also place this at the end of a line with a comment
  • Enter the following in your script Introduction.R but don’t do anything else
# Create an object called x
x <- 1:5

RStudio: The Script Window

# Create an object called x
x <- 1:5

To send this to the Console:

  • Place the cursor on the line with x <- 1:5 then Ctrl+Enter (Cmd+Enter on OSX), or
  • Select one or more entire lines using the mouse then Ctrl+Enter (or Cmd+Enter)
  • Or after selecting one or more lines you can click the Run button
    • Be careful to select all the correct text though
    • It’s very easy to miss the first character
  • This will have overwritten our previous object.
  • Check the Environment Tab to see the changes

RStudio: The Script Window

As well as creating objects, we can write general code

# x is a vector. How many values are in the vector?
length(x)
[1] 5

Enter this in your Script Window then send to the Console

Sometimes, we copy the output back to the Script Window if it’s important

length(x) 
# [1] 5

Including comments describing your intention, is highly advisable

RStudio: The Script Window

When we executed length(x) did we create a new object?

No, we just called the function length() and executed it on x

The output of the function was simply printed to the console

Vectors

Vectors

  • The object x is a vector \(\implies\) fundamental structure in R
    • Like a single column in a spreadsheet
  • In R when we pass a vector to a function, the entire vector is evaluated
    • No need to select a column from your spreadsheet

Add the following to your script

# Are any values of x are greater than one?
x > 1
[1] FALSE  TRUE  TRUE  TRUE  TRUE

Notice we have a value returned for each element of x

Vectors

  • Enter the following in your script with your own comments
    • Execute in the Console
    • Some will return 5 values, others will be single values
x^2
sqrt(x)
max(x)
sum(x)
mean(x)
sd(x)
typeof(x)

Discuss what you think the values mean as you write your comments

Vectors

  • x clearly contains numbers (i.e. integers)
    • Can be checked using typeof(x)
    • A vector only contains one type of value
  • Vectors can also contain characters
    • We cannot perform calculations on these vectors
    • Some functions do work though

Vectors

  • Enter the following in your script then execute
# R has an inbuilt vector with the lower case letters of the alphabet
letters
# How many letters are in this vector?
length(letters)
# Can characters have a maximum value?
max(letters)
# Can we add characters to find a sum?
sum(letters)

Subsetting Vectors

  • We can subset vectors using square brackets []
# What are the first 5 letters of the alphabet?
letters[1:5]
[1] "a" "b" "c" "d" "e"

Vector Types

R has 6 types of atomic vectors \(\implies\) only 4 are commonly used

  1. logical: Can only contain TRUE or FALSE
    • Are binary (i.e. single-bit) values
  1. integer: Only contains whole numbers
    • 32 bit upper limit
  1. numeric: Contains numbers with decimal points (aka doubles)
    • Larger memory requirements than integers
  1. character

Remaining types are:

  • complex (sqrt(-1))
  • raw holds raw bytes charToRaw("abc")

Examples

A logical vector is returned by a logical test

# This returns a logical vector the same length as x
# Let's save the output as a new vector using the <- symbol
logi_vec <- x > 1
logi_vec
[1] FALSE  TRUE  TRUE  TRUE  TRUE
typeof(logi_vec)
[1] "logical"

Taking square roots will return values with decimal points

# The square roots have decimal points so they are doubles
dbl_vec <- sqrt(x)
dbl_vec
[1] 1.000000 1.414214 1.732051 2.000000 2.236068
typeof(dbl_vec)
[1] "double"

Coercion

  • Vectors can be coerced to other types
# Coercing x to a character vector will show every element with quotation marks
char_vec <- as.character(x)
char_vec
[1] "1" "2" "3" "4" "5"
typeof(char_vec)
[1] "character"
  • Can easily coerce in order of complexity without information loss
  • Information is lost going backwards
as.integer(logi_vec)
[1] 0 1 1 1 1
as.logical(x)
[1] TRUE TRUE TRUE TRUE TRUE

Advanced Subsetting

  • We could use our results from the logical test to subset x
# These two commands return the same vector
x[x > 1]
[1] 2 3 4 5
x[logi_vec]
[1] 2 3 4 5
# This returns the positions within logi_vec which are TRUE
which(logi_vec)
[1] 2 3 4 5

Creating Vectors

  • Normally to create vectors we use c()
    • Stands for combine (i.e. we combine vectors)
    • Is an empty vector (i.e. NULL) by default
c()
NULL

Creating Vectors

  • Add your own comments to describe the following
# Make a vector of doubles with names for each value
rnd <- c(a = 1, b = 5.2, c = 100, d = 3.1)
rnd
length(rnd)
typeof(rnd)
rnd > 5
which(rnd > 5)
rnd[rnd > 5]
names(rnd)
rnd["b"]

Conclusion

  • Make sure you save the file Introduction.R
  • This is now a complete R Script
    • Can be re-run at any time in the same order
    • Will always produce identical results
  • We’ve also (accidentally) learned about vectors
    • Will be super helpful for the rest of the workshop
  • Vectors are the most fundamental structure in R