Chapter 2: A Primer on R Programming
THIS CHAPTER IS OPTIONAL
Preamble
Learning Outcomes
This chapter is optional. The objective is to introduce you to R programming. The dartRverse package does not require an in-depth knowledge of R programming, so those not wishing to dive deeper into the R programming aspects of SNP data analysis can skip this chapter.
After completing this chapter, you should have a basic understanding of the fundamentals of the R language and programming in R. This includes how to import data into the R workflow, an understanding of the data structures R uses to hold data, and how to manipulate those data with assignment statements, conditional statements and iteration statements.
Most importantly, you should be empowered to expand your knowledge beyond the basics presented here by knowing where to find information on R operations and capabilities and how to access it.
Prerequisites
![]()
RStudio is required to work through this chapter so you will need to have already completed Chapter 1. RStudio Refresher.
You will have been introduced to the concept of assignment using the <- operator in Chapter 1. This knowledge is assumed.
![]()
You may also find it helpful to listen to a podcast summary of the introductory material in this chapter.
Workflow
This chapter follows a formula. First, some Theory, unencumbered by competing options and technical asides, then some Worked Examples where you are led through analyses using RCode Boxes, then some Practical Nuances, finishing with some Exercises where you are left on your own to integrate the knowledge you have gained in a problem-solving context.
Because this is an optional chapter, the Worked Examples may be treated as revision, and the code run within the RCode Boxes without referring back to RStudio. Or you can progressively copy the code to your RStudio Editor to execute it and explore more options on your own.
Additional Reading
For more advanced treatment of R programming refer to the official documentation. There are also innumerable tutorials on R programming available online, each with its strengths and weaknesses. To expand your knowledge and gain experience in advanced topics in R programming, you should select one of these resources that best suits your tastes. We recommend the R Programming course from the R package. You might also like to refer to the online short course Introduction to R by Jonathan Cornelissen.
Cheat Sheets are also good to have at hand. There is one on R programming and one on functions that are particularly useful.
Session 2-1: Key Programming Concepts
What is R?
We introduced R briefly in Chapter 1. R is a specialised programming language that has become the go-to tool for statisticians, researchers and data scientists worldwide.
What sets R apart is its vast ecosystem of specialised packages that extend its capabilities into virtually every field of research, from genomics and climate science to finance and marketing analytics.
The language’s strength lies in its ability to seamlessly combine data manipulation, statistical analysis, and visualisation in a single environment, allowing users to import raw data, clean and transform it, perform sophisticated analyses, and create publication-quality graphs all within the same workflow.
While R has a steeper learning curve than point-and-click software, its power and flexibility make it invaluable for anyone working with substantial datasets or requiring advanced statistical techniques. The fact that R is completely free and open-source has contributed to its widespread adoption in academia and increasingly in industry, where organisations appreciate both its cost-effectiveness and the reproducible, transparent nature of R-based analyses.
The versatility of R has led to many different styles in the way the program is used. A programmer will use R in a very different way from someone using R to undertake statistical analyses. This module presents only one style. As your skills develop and you learn more about the capabilities and options of the programming language, you will develop your own style.
R as a Programming Language
![]()
R is a programming language combined with the features of a statistical package. As with most programming languages, R comprises:
- A set of keywords and operators that the programmer combines to form statements or instructions to be executed. R is unusual in that many of its commands are function calls, and so its keyword set is largely made up of the function names.
- A clearly defined sequence in which these instructions are executed.
- Data Structures for holding data to be used in analyses.
- Mechanisms for input and output of data to those structures, often referred to as I/O.
- A mechanism for branching, subject to some condition being met.
- A mechanism for iteration, that is, repeated execution of a sequence of statements while a condition is met until a condition is met, or some fixed number of times.
If you think in these terms, once you learn one programming language you can move quickly to another programming language. We will learn more about these concepts as we move through the practical components of this Module, not necessarily in this order.
# Read the data from the clipboard, tab delimited
# Note: Cut from Excel
forest <- read.delim("clipboard")
# View the contents of the dataframe forest to confirm
forest
# Make dataframe forest the default
attach(forest)
# calculate timber yield separately for each species
yield <- vector(1:length(species))
for (i in 1:length(species)){
if (species[i] == "radiata") {
yield[i] <-
density[i]*3.1416*diameter[i]*height[i]*0.85
} else {
yield[i] <-
density[i]*3.1416*diameter[i]*height[i]*0.62
} # Terminate the if statement
} # Terminate the for loop
# Add yield to the dataframe forest
forest <- cbind(forest,yield)
# Examine forest to confirm
forest
Figure 2-1. A simple R Program. The program is executed in sequence one statement at a time from the top. The “for” statement results in the enclosed code being repeated for each line of data. Branching is provided with an “if” statement.
The script in Figure 2-1 illustrates many of these elements. The R script has a syntax (keywords and operators) unique to the R programming language. It is read and executed from top to bottom (sequence). It contains code for branching (the if statement) and for iteration or looping (the for statement). The I/O is evident in reading an Excel spreadsheet and in outputting the results locally to the screen.
| Copy the script and pass it to your AI Client with a request to explain the code to you. Ask your AI Client to critique the code. |
Unique attributes of R
![]()
R differs from other programming languages conceptually, structurally, and philosophically. Many of these differences arise because R was explicitly built for statistics and data analysis, not for general-purpose computing.
- R works with objects, that is, with self-contained entities with defined attributes. These entities may be a scalar value, a vector of values, a matrix or even a function. The advantage of objects is that when you use one in calculations, R knows what the object is from its attributes and how to handle it in the calculations.
- R uses vectorised operations, meaning you can perform calculations or comparisons on entire datasets at once, without writing loops.
- Many statistical and graphical functions are built-in, such as
lm()for linear modelling,t.test()for testing means andplot()for displaying data. - Because functions are objects, functions can act upon functions, as do members of the
apply()family of functions for example. - Variables in R don’t need type declarations — they adapt dynamically. This is both a feature and a fault depending upon context.
- The R scripts are interpreted rather than compiled so the programming environment is interactive and exploratory, which encourages incremental development of scripts and visualisation of results as the analysis progresses.
- R employs functions that have a single object returned rather than the more flexible subroutines available in other languages.
- R is not a structured language like C++, though more structured than Perl. This means that some discipline needs to be applied if your R programs are going to be useful to the future you or others who may come to take over your programming responsibilities.
- R is slow to execute in comparison with general purpose compiled programs like FORTRAN or Julia.
Good Programming Practice
Logic
- Work out the logic of your programming task before beginning to code.
- Structure your R scripts according to best-practice principles. A good, structured script uses a hierarchy of logical control structures — each with a single-entry point and a single exit point. Then the flow of execution can be readily understood top-to-bottom.
- Avoid jumping around the script or using esoteric code such as changing global variables inside a function. It might be clever, but it is counterproductive when working in a team.
Style
- Use consistent naming conventions such as
item_caseoritem.casefor variables and functions, and a different convention for scripts. - Comment profusely using the
#operator (see Figure 2-1) and explain why, not just what. - Indent statements within
ifandforconstructs to clearly show the body of commands that apply within these constructs. - Group related code using blank lines and section headers, e.g.
##### DO THE JOB
There are some good style guides to follow such as the Tidyverse style guide, which will help with consistency.
Functions
- Encapsulate repeated tasks, even small ones, into functions.
- Include defensive checks and defaults in functions. Artificial Intelligence aids are good at identifying and trapping potential sources of error.
- Use Roxygen comments (
#') for documentation at the head of your functions.
Computations
- Avoid explicit loops when vectorisation is possible, for example
# Bad
for (i in 1:length(x)) y[i] <- x[i]^2
# Good
y <- x^2
- Remove from loops evaluations that can be done before the loop is executed.
- Load only what you need. Do not import an entire package if you are to use only one of its functions. Use
importFrominstead. - Remove objects that are not to be used again, with
rm().
Clarity over efficiency
Remember, R programming is as much about clarity in communication as it is computation. Readable, reproducible and thoroughly tested code is more valuable than clever code that is comprehensible only to you, and likely not comprehensible even to you weeks or months later.
Session 2-2: Worked Examples
To access the Worked Examples, navigate to the RStudio Tutorial Pane and then open the session by clicking eBook Getting Started with dartRverse and navigate through the menu to the worked examples listed below.
| Worked Example 2-1: Data Structures
This worked example will run through R programming using various data structures called objects. |
| Worked Example 2-2: Input/Output
This worked example introduces R programming for importing and exporting data into the data structures covered in the previous session. |
| Worked Example 2-3: Controlling workflow
This worked example introduces R programming for controlling workflow using IF and FOR constructs and other elements specific to the R programming language. |
| Worked Example 2-4: Functions
This worked example introduces R programming for user-defined functions. |
Session 2-3: Practical Nuances
When things go wrong
There is a dreaded shadow that hangs over all who engage in computing — SYNTAX. If you don’t get it right, the program will not work. Finding out why it will not work is not always easy, though many simple mistakes will be immediately evident.
AI Tools like Claude and ChatGPT have revolutionised our approaches to debugging our scripts. Both are fully familiar with R and dartRverse. They are not infallible but are of immense value in identifying bugs and potential logical flaws in your programming.
Nevertheless, we provide some advice on how to proceed with manual troubleshooting.
Help tools – first port of call
?summary |
# Get help for a specific function |
??regression |
# Search for functions related to "regression" |
help.search("mean") |
# Search help files for a term |
Failure to Balance Quotes
String values are usually identified as such by enclosing them in quotes. If you fail to supply the terminal quote, a very common error, then R passes all that follows the initial quote into the string variable. Usually this is evident because the R Console responds with a + rather than the usual command prompt >. You need to break out of this using the Esc key, locate and rectify the error, and resubmit the code.
Failure to Balance Brackets
Many R commands comprise nested function calls, and so you have brackets within brackets. These two need to be balanced. Blocks of code also are contained within brackets ({ and }), and these need to be balanced. RStudio will identify balanced brackets to assist with debugging. Merely mouse-over a bracket to highlight its counterpart, or press Ctrl + P to jump between the opening and closing bracket.
Package not loaded
glPCA()
Error in glPCA() : could not find function "glPCA"
When drawing functions from third-party providers, you need to first install the package with install.packages("new.package") and then load the package with library(new.package).
Incorrect syntax for function calls
R functions are very particular in what they expect as arguments, and often the order of the arguments is quite important. When a function fails, the first step is to call up the help files using the ? prefix. An example is
?summary
This command opens up the help files in a new window. The help information contains full details of the syntax for the summary() function, which should enable you to identify and rectify the problem with your program.
Mixing Up Characters with Numbers
Misspelling variable names and function names is a very common mistake, and one that requires attention to detail. A common mistake is to use a lowercase L (l) in place of the number one (1) or the letter O in place of the number 0. Look for this when your program does not work for reasons that are not immediately obvious.
Mixing Up Variable Names with Function Names.
It is best to avoid using the pre-existing names of R functions as variable names. For example, avoid using length as the name of a variable when there exists a function length() that returns the number of values in a vector. This can lead to considerable confusion – length(length) for example – and is best avoided.
Object Does Not Exist
This is a common error and can arise for reasons as simple as misspelling its name, or for more complex reasons such as the object not falling on the search path.
The first step is to check that the object exists by typing its name and submitting it to the R Console. This will verify its existence and display its contents.
If the object is part of a larger object, such as a dataframe, R might not be able to find it. You can identify this problem by typing its full specification, such as my.data$Wt.
Debugging
Debugging a program is what programmers do, but for those not used to programming, it can be a real block. The idea is to be systematic about your approach to identifying and rectifying bugs in your programs.
The best way is to run each line of your program one at a time, checking the progress of the analysis. Bugs often beget bugs, so it is important to start at the top of the program.
Bugs derived from incorrect syntax are the easiest to resolve. Those involving logical errors take a bit more mental energy.
Exercises
Now is a good time to try some more of what you have learned so far on some exercises and your own data.
The Exercises are also found by navigating to the RStudio Tutorial Pane and then open the session eBook. Navigate from there to the exercises under Chapter 2.
Winding Up
Where have we come?
![]()
We have learned that there are multiple elements to consider when using any programming language, including
- I/O – how to read data into R and output results to the console or to disk.
- Data structures – how R stores data in dataframes, vectors, matrices, arrays and lists.
- Computational elements fundamental to all programming – keywords, sequence of progression, branching and iteration.
- Functions – the special role of functions in R, built-in functions, third-party functions and functions you construct yourself.
You also should now have
- Gained detailed knowledge of the tools for undertaking computations on data held in the various R data structures.
- Come to understand how data structures that contain the results of these computations can be output to disk as csv files, text files or compact binary files.
Through the worked examples, you should appreciate how this all hangs together in the form of R scripts.
Most importantly, you should be empowered to expand your knowledge beyond the basics presented here by knowing where to find information on R operations and capabilities and how to access it. Modern tools such as AI Clients are invaluable in assisting you to rapidly build capability for R programming.
Where have we not gone?
Graphics
R has outstanding capabilities in graphics. We have not touched on these capabilities. That is left to the many guides and books available on this topic, and for AI to assist you in writing code to produce publication-ready graphics.
Tidyverse
Tidyverse and other related programming tools in this family are used by many programmers to enhance productivity. We have focused largely on base R as a foundation from which to build your learning. It is a matter of taste as to whether you want to take advantage of the power of tools like Tidyverse.
Ende