Ecosystem, Variables, and Operations
R code can be saved in a text file with the extension .R. You can then run the code in the R console or RStudio by sourcing the file using the source() function. For example, if you have a file named my_script.R, run it with source("my_script.R") in the R console.
You can save your R code in a file with the extension .Rmd or .qmd. This allows you to create dynamic documents that combine R code, text, and output. For example, the presentation slides are made from an improved version of .qmd.
You may save your data or functions to an .RData file and load it with load("PATH/TO/THE/DATA_FILE.RData").
Pro tips
R is a programming language popular for statistical computing, elegant graphics, and genomic data analysis.
Features
Slide conventions
This or This are code.R provides many arithmetic and statistical operations like +, -, *, /, %%, and ^
Variables store information. To save a value, assign it to a variable. The assignment operator in R is <-. Occasionally, you may also see = used for assignment, but <- is the preferred style in R.
\[ \small \text{Variable <- Value} \]
Benefits of using variables:
Variables can be called just about anything, but there are some rules in R:
$, #, %, or spaces are not allowed.age, Age, and AGE are different variables).TRUE, FALSE, if, else, or function as variable names as they are reserved for other purposes in R.Variables can store different types of data, and R has several built-in data types to support them. The data type of a variable determines what kind of values it can hold and what operations can be performed on it.
You can use the class() and typeof() functions to check the class and data type of any variable. R has five common data types:
The numeric data type is for numbers.
typeof() reports double.The integer data type stores whole numbers.
L suffix to create an integer value.as.integer().as.numeric().In R, the logical data type can be:
TRUE (carries a value of 1)FALSE (carries a value of 0)Tips: Logical values can behave like numbers. Numeric operations are possible on logical values, but use caution.
The character data type stores text strings, including letters, numbers, and symbols. Strings in R can be written with single or double quotes.
Comparison operators compare two values and return a logical value TRUE or FALSE.
while performing any operations mixed with different data types in R, the values are automatically converted to the most general data type by coercion. The order is as below
\[ \text{logical} < \text{integer} < \text{numeric} < \text{character} \]
Functions are used to perform tasks on input values. For example, the sin() function calculates the sine of a number. The input to the function is given inside the parentheses.
sin is the name of the function, and pi is the input. The output of the function is 0.0? This is because π is stored as a double and is accurate to about 15–16 decimal places. As a result, sin(pi) is a very small number close to zero, but not exactly zero.Another example is floor(), which rounds a number down to the nearest whole number.
floor(sin(pi)) is 0. This is because the floor() function rounds down the value of sin(pi) to the nearest whole number.? to get help on a function. For example, ?floor gives information about the floor() function.You can customize functions in R to perform specific tasks. Benefits of using functions:
The format for writing a function in R is:
\[ \begin{aligned} \textit{function_name} &\leftarrow \text{function}(\textit{arguments}) \{ \\ & \textit{your code} \\ & \} \end{aligned} \]
Consider the following example of a function that calculates BMI:
# First define a function to calculate BMI
# weight in kg, height in meters
calculate_bmi <- function(weight, height) {
bmi <- weight / (height^2)
return(bmi)
}
# Example usage:
yuanhua_weight <- 66.2
yuanhua_height <- 1.71
ray_weight <- 68.1
ray_height <- 1.85
calculate_bmi(yuanhua_weight, yuanhua_height)[1] 22.63944
[1] 19.89774
Data structures are one of the most important features in programming.
Benefits - Easier to read - Fasten calculation
Main data structures used in R:
Vector: A list of items of the same data type, like a series of numbers (numeric) or words (characters).
Matrix: Tables of numbers with rows and columns, where all elements are the same type.
List: Collections that can hold different types of data all together, such as numbers, words, or even other lists.
Data Frame: Like a spreadsheet where each column can have different types of data, useful for tabular data
typeof() functionlength() function.See more introduction here.
There are also different ways to automatically generate vectors
There are also different ways to automatically generate vectors
Vectors can also be combined from other vectors.
[1] 1 2 3 4 5 6 7 8 9 10 11 12 32 49 8 29 47 4 50 50 50
[1] "double"
Did you notice that new_vector is now a of type double ?
You can spend a few minutes to create vectors and explore what happens to the data type of the vector when you combine them with others.
Items in a vector can be directly retrieved by their index
Can you write the code to retrieve the scores from:
Using the index it is possible to modify specific items in a vector
[1] 44 56 63 75 77 78 81 90 93 99
dim() function.See more introduction here.
Accessing items in a matrix is similar to vector but in 2 dimensions
Modifying items in a matrix is similar to vector but in 2 dimensions. Can you write the code to:
list can contain a list of any data structure: value, vector, matrix, list, etc.List of 5
$ : num 1.7
$ : logi TRUE
$ : int [1:3] 1 2 3
$ : chr "Ray"
$ :List of 3
..$ : num 8
..$ : num 8
..$ : num 4
We can use str() function to view the structure of a list (or any object).
$ symbol with the name.Can you retrieve the Height and Name from myList?
note that unlike the above, the retrieved values are still in a list as opposed to individual values like what you get with double brackets [[]]
It is possible to inter-convert list to and from vectors.
# example of interconverting list to vector and back
myList <- list(1.70, TRUE, 1:3, "Jason")
str(myList)List of 4
$ : num 1.7
$ : logi TRUE
$ : int [1:3] 1 2 3
$ : chr "Jason"
[1] "1.7" "TRUE" "1" "2" "3" "Jason"
List of 6
$ : chr "1.7"
$ : chr "TRUE"
$ : chr "1"
$ : chr "2"
$ : chr "3"
$ : chr "Jason"
Data frame is widely used for rectangular data, where each column has the same data type (vector) but different columns can have different data types (like Excel)
The data frame is in fact a special type of list: A list of vectors with the same length.
myDF <- data.frame("Height" = c(1.70, 1.80, 1.68, 1.72),
"Weight" = c(67, 60, 55, 58),
"Name" = c("Jason", "Ray", "Dora", "Yuanhua"),
"Gender" = factor(c("male","male","female","male")))
myDF Height Weight Name Gender
1 1.70 67 Jason male
2 1.80 60 Ray male
3 1.68 55 Dora female
4 1.72 58 Yuanhua male
[1] "Dora"
[1] "female" "male"
| Operator | Description | Example | Returns |
|---|---|---|---|
== |
Equal to | 5 == 5 |
TRUE |
!= |
Not equal to | 5 != 7 |
TRUE |
> |
Greater than | 10 > 8 |
TRUE |
< |
Less than | 2 < 4 |
TRUE |
>= |
Greater than or equal to | 5 >= 5 |
TRUE |
<= |
Less than or equal to | 3 <= 5 |
TRUE |
Logic operators are used for operating on logic data type (i.e. TRUE or FALSE). The three logical operators are:
&|![1] TRUE
Link logical outcome to an action given the condition. This is where the if and else statement comes in. The format is like
if (CONDITIION) {
# If CONDITIION==TRUE: codes inside this bracket will be executed
} else {
# If CONDITIION==FALSE: codes inside this bracket will be executed (You can akso omit this part if needed)
}Example
[1] "Zoom link:XXXX"
It is also possible to chain if/else statements if there are multiple conditions:
Here are some simple examples of a for loop in R:
[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
[1] 6
[1] 7
[1] 8
[1] 9
[1] 10
You can also iterater on vectors
When R throws red text at you, first determine what kind of message it is:
Removed 5 rows containing missing values). Action: Read it, verify if it affects your analysis, but no immediate panic.Don’t read the whole error if it looks messsy. Look for the recognizable words at the end of the message.
Common Biomedical Data Errors translated to plain English:
Error: object 'XXX' not found
XXX yet, or you made a typo (e.g., you typed xxx).Error in read_csv("FILE") : could not find function "read_csv"
could not find functionlibrary(tidyverse) or library(readr) first.Error: unexpected symbol in "ggplot(data = clinical_df aes(x = treatment))"
unexpected symbolclinical_df).When the error is confusing, Large Language Models (LLMs) are your best teaching assistants. However, “Garbage In = Garbage Out.”
Bad example
My R code doesn’t work!!!!!
Asking right question
To get an immediate, accurate fix, always provide the AI with these three components:
Act as an expert R programmer
Goal: I am trying to [e.g., create a scatterplot of gene expression versus patient age using ggplot2].
Here is my code:
Here is the error message I received:
Please tell me what went wrong and provide the corrected code.
could not find function..., reply to the AI with that new error!str(your_data) or head(your_data) and mock up the values, or simply provide the column names.This notebook adapts contents from these resources:
Special thanks to Prof. Yuanhua Huang, and Prof Jason Wong.