9 * 5[1] 45
Don’t we all know it? Summer ends and we’ve forgotten where we left off before the break. Has this happened with your R programming? No problem! In this session, we’ll refresh your R skills and give you a boost for the upcoming academic year. On 6th of October, we will cover the technical basics (basic syntax, how to run R scripts, and how to install and load packages), simple data processing (how to import and explore your data), and basic visualization (using base plots and ggplot2).
Before we start looking at how to use R to analyze your data, let’s have a look at the technical basics. We will refresh how to name objects, how to use comments, what a function is and how to find out which arguments it needs. After that, we will shortly look at data types and how to run RScripts and how to install and load packages.
You can use R similar to a calculator. It is possible to just type in numbers into your console and receive results immediately.
9 * 5[1] 45
Everything that you create (and that exists) in R is an object. To be able to use them efficiently, we can name objects. For that, we use the assignment operator <-.
result <- 9 * 5If we want to print the value of an object, you can run a line that just contains the object name.
result[1] 45
R offers various in-built functions, i.e., a block of code that runs when the function is used. To use a function, we use its name and provide it with the needed arguments, i.e., the input that the function needs to run. In the following example, we use the function sqrt to calculate the square root of 4.
sqrt(4)[1] 2
If you want to know more about a function, you can use the ? to access the documentation.
?sqrt()In R, vectors are a commonly used data type. Vectors consists of a series of values which can be connected using the c()-function.
my_vector <- c(1,2,3,4,5) # 1,2,3 are numeric data types
my_vector[1] 1 2 3 4 5
We can also store characters in a vector. Characters are indicated with " ".
my_second_vector <- c("these","are","characters") # these words are seen as character data type
my_second_vector[1] "these" "are" "characters"
Aside from numeric and character data types, R also allows to use logical data (TRUE vs. FALSE), integer, complex and raw.
You can use various function on vectors (and even subset them). Commonly used are the following:
length(my_vector) # returns the length of the vector[1] 5
typeof(my_vector) # returns the type of the vector (e.g., character)[1] "double"
str(my_vector) # returns an overview of the structure of the vector num [1:5] 1 2 3 4 5
You can run R code either through the command line or by using an R script. Usually, you run the code line by line. An example of an R script can be found in our Programming Café session on IDEs in which we present how RStudio can be used to run R scripts.
To install new packages, you can use the command install.packages("PACKAGE"). To import packages and use them in your code, use library(PACKAGE). The following example shows how to install and import ggplot2.
```{r}
install.packages("ggplot2")
library(ggplot2)
```While we cannot cover data analyses in this short session, I want to shortly remind you how to import, explore, slightly manipulate and visualize your data.
You can import your data with the help of various packages. The most straight-forward way is to use one of the following functions:
# Read file in table format (each row is one line in the document)
data <- read.table(file = "material/example.csv", header = TRUE, sep = "\t")
# import file with sep = "\t"
data <- read.delim(file = "material/example.csv")
# import .csv file
data <- read.csv(file = "material/example.csv") You can have a look at your data with various in-built functions. The following overview is taken from the Data Carpentry for SSH workshop and adapted to fit our example:
dim(data) # - returns a vector with the number of rows as the first element, and the number of columns as the second element (the dimensions of the object)[1] 44 4
nrow(data) # - returns the number of rows[1] 44
ncol(data) # - returns the number of columns[1] 4
head(data) #- shows the first 6 rows name age group temperature
1 Peter 11 junior 37
2 Alex 25 adult 41
3 Sandra 43 adult 35
4 Eva 55 adult 38
5 Adam 66 senior 39
6 Marijn 7 junior 41
tail(data) #- shows the last 6 rows name age group temperature
39 Henny-Dani 59 adult 38
40 Jaimy-Henny 54 adult 40
41 Jamie-Ali 63 adult 40
42 Dominique 12 junior 37
43 Jaimy-Sam 12 junior 40
44 Robin-Jaimy 69 senior 37
names(data) #- returns the column names (synonym of colnames() for data.frame objects)[1] "name" "age" "group" "temperature"
str(data) #- structure of the object and information about the class, length and content of each column'data.frame': 44 obs. of 4 variables:
$ name : chr "Peter" "Alex" "Sandra" "Eva" ...
$ age : int 11 25 43 55 66 7 78 63 69 63 ...
$ group : chr "junior" "adult" "adult" "adult" ...
$ temperature: int 37 41 35 38 39 41 38 35 37 41 ...
summary(data) #- summary statistics for each column name age group temperature
Length:44 Min. : 1.00 Length:44 Min. :35.00
Class :character 1st Qu.:13.00 Class :character 1st Qu.:36.00
Mode :character Median :44.00 Mode :character Median :38.00
Mean :39.07 Mean :38.05
3rd Qu.:63.00 3rd Qu.:40.00
Max. :78.00 Max. :41.00
As two categories of our data consists of characters, we might want to make one of them categorical. We can do that by casting them as factors using the as.factor()-function. We address the specific column using $.
data$group <- as.factor(data$group)Creating a base plot in R is as easy as typing plot(data).
plot(data)
For our data, the plot is not really helpful, but you can also focus on one specific column instead using $ to indicate the column name.
plot(data$group)
plot() allows for multiple other arguments to be used. You can find more information on it here.
A handy package to create plots is ggplot2. You can find a manual on how to visualize your data with it here.
Comments
Comments are a programmers friend. They help you to keep an overview of your code, understand what you did (and why) and keep your code readable. In R, you can use the
#character to create a comment. You can do this either behind a line of code, above or below it.You can also use comments to exclude specific lines of code from being run. To do that, you “comment out” a line of code. In the following example, we commented the line out that assigns
bthe new value20.