R is a statistical and graphical software package, and is very commonly used in many disciplines, including data science, statistics and the environmental and biological sciences. RStudio is an integrated development environment for R, which is a programming language for statistical computing and graphics. The great strengths of R for the research community are:
The objective of this orientation is to introduce you to RStudio and its basic functions, and to provide you with tools and resources to continue learning on your own.
By the end of this orientation, we will have covered:
In preparation for today’s orientation, you should have already downloaded and installed R and RStudio to your computer. You should have also received and downloaded the Excel dataset dummy_KAPB.xlsx.
When you first open RStudio, you will encounter an
interface with three panels.
To get started, open a new R script by clicking File -> New File -> R Script. A new panel will appear, which is the new R script.
The four panels in your view are:
Projects are a way to work in RStudio so that all inputs and outputs are stored in one place. It means that more than one user can run the same analyses without defining new file paths.
It is good practice to set up a project and associated file structure:
The next step is to use the file explorer on your computer to locate the
folder you just created.
Return to RStudio. Before moving on, we need to save the script that we created.
A simple way to start using R is as a basic calculator. You can write equations in the script or in the console.
To run commands in the console:
To run commands in the script:
5 * 10
## [1] 50
Both times, the equation and the output will appear in the console.
You can also run simple mathematical functions, including
log(), sqrt(), exp(), etc.
For example, to calculate the square root of 25:
sqrt(25)
## [1] 5
sqrt is an example of a
function. A function is a code operation that accepts
inputs and returns a transformed output.
To find out more about a function, you can type “?” followed by the function name in the console.
?sqrt
Errors happen all the time when coding in R! You will probably encounter error messages during this orientation. Learning how to identify and correct errors is a big part of learning how to code.
When an error occurs, R will respond with an error message which will help you determine what went wrong. Try running the following commands, and see the error messages that appear:
sqrt(a)
sqrt("25")
SQRT(25)
sqrt(25))
If your code isn’t working, try checking:
When writing code in new R scripts, it is good practice to annotate your code with comments. This allows you to organize your code, and to document what the code is doing.
To type a comment, place your cursor in the script and type
# This is a comment.
# This is a comment.
R understands that any lines in the script with the #
mark in front of them are not commands, and should not be processed.
You should use comments throughout this orientation to annotate the script you write, to make it easier to understand in the future.
You can assign numbers to different variable names. Type the following into your script, and press Ctrl+Enter to run the commands:
my_number <- 20
my_number
## [1] 20
The <- operator tells R to assign the number on the
right to the variable name on the left. The keyboard shortcut for typing
<- is:
Alt+-.
After running the above commands, you will notice that a new object called my_number has shown up in the Environment in the top right. This means you have created and stored my_number in this R session.
Anything you store in R using the <-
operator (datasets, variables, a list of village names, a total
population of inhabitants, even results such as graphs) are
objects that are assigned a name and can be referenced
in subsequent commands.
You can run mathematical operations using variables that are numbers. For example:
my_number * 5
## [1] 100
Strings are like numbers, but typically consist of text, or characters. Create a string variable by typing the following into your script:
my_string <- "avocado"
my_string
## [1] "avocado"
Variables that are strings cannot be used in mathematical operations. Try the following, and see the error message that appears:
my_string * 5
The error message informs you that you cannot perform that operation because the variable is non-numeric.
You can determine what type of data your variable is using the
class() function.
class(my_string)
## [1] "character"
Vectors represent a set of variables (numbers or strings) in an
order. To create a vector, we can use the function c(),
which is short for “concatenate”, or “combine”. Type the following in
the script:
v1 <- c(1,2,3,4,5)
v2 <- c("avocado","banana","mango")
You can calculate summary statistics of numerical vectors, like
vector v1 that you just created. Try these commands in your
console:
mean(v1)
## [1] 3
max(v1)
## [1] 5
sum(v1)
## [1] 15
length(v1)
## [1] 5
length(v2)
## [1] 3
At this point, you have created several R objects. In the upper
right-hand Environment you will see all of these
objects listed, along with some of their characteristics.
R Packages are collections of functions and datasets that have been developed by the R community. Packages can improve base R functions and add new functions.
There are two steps to using a package:
First, we will install a package called readxl that will
later allow us to import Excel files to R.
install.packages("readxl")
In the console, you will see a message when the package has been successfully installed.
When we want to use the package, we load it using the
library() command.
library(readxl)
Normally when we use R, we are using external data sources. We can import data sources into a data frame in R. Data frames are tables that are used for storing data, similar to an Excel spreadsheet.
Let’s import the dataset that you earlier saved in the
data folder. This operation will use the
read_xlsx() function that is part of the
readxl package we just loaded.
dat <- read_xlsx("data/dummy_KAPB.xlsx")
The Excel sheet has now been imported as a data frame with the name dat. You will see it listed in the upper right-hand Environment.
We have multiple ways of viewing a data frame in R studio. One easy
way is using the str() function, which is short for
“structure”. This function will show you all the variable names and
types in your data frame.
str(dat)
## tibble [49 × 14] (S3: tbl_df/tbl/data.frame)
## $ today : POSIXct[1:49], format: "2023-05-24" "2023-05-24" ...
## $ consent : chr [1:49] "yes" "yes" "yes" "yes" ...
## $ country : chr [1:49] "uganda" "benin" "cotedivoire" "nigeria" ...
## $ sex : chr [1:49] "F" "M" "M" "M" ...
## $ age : num [1:49] 55 28 38 30 35 25 33 31 30 53 ...
## $ occupation : num [1:49] 7 7 2 1 5 5 9 9 9 7 ...
## $ specify_occupation : chr [1:49] NA NA NA NA ...
## $ qualifications : num [1:49] 4 4 4 4 4 4 4 4 3 4 ...
## $ year_graduate : num [1:49] 1997 2016 2018 2016 2013 ...
## $ years_experience : num [1:49] 26 7 5 7 11 3 11 6 2 32 ...
## $ average_hours_day : num [1:49] 8 9 24 8 8 10 8 10 10 6 ...
## $ current_diagnose_treat_rdts : num [1:49] 1 1 1 1 1 1 1 1 1 1 ...
## $ rdt_false_negative : chr [1:49] "no" "yes" "no" "no" ...
## $ specify_treat_negative_rdt_no: chr [1:49] NA "You can't treat patient with a negative results" "Examine the person" "Because the result shows negative so I will go for further investigation" ...
Other useful functions include head() which will show
the first several rows of your dataframe; and View() which
will open a new tab where you can see the data as a spreadsheet. You can
also access this view by clicking on the data frame from the
Environment.
View(dat)
head(dat)
We can use some of the skills we’ve already learned along with a few new functions to continue exploring the data.
For example, we may want to know the type of data in the different
columns. We can use the class() function again, along with
the $ operator to specify a specific column in a
dataframe:
class(dat$country)
## [1] "character"
class(dat$age)
## [1] "numeric"
Another useful way to summarise data is by generating frequency
tables. For example, if we want to know the distribution of males and
females in the data, we can use the table() function:
table(dat$sex)
##
## F M
## 26 23
If we want to get more granular, we can use the same function to see the distribution of males and females, by country:
table(dat$country, dat$sex)
##
## F M
## benin 2 7
## cotedivoire 3 2
## nigeria 11 9
## uganda 10 5
For the next set of exercises, we will use a group of packages that
have been designed to work together to do common data science tasks.
This group of packages is called the Tidyverse, because
it is designed to work within the “tidy” data
philosophy.
Under the tidyverse data model, data should have the following format:
Throughout the rest of the tutorial, we will use a set of R
packages for manipulating data and creating plots that exist under the
umbrella of the tidyverse.
First we need to install the packages, and then load them. Once packages are installed, you do not need to install them again.
install.packages("dplyr")
install.packages("tidyverse")
install.packages("tidyr")
Next we load packages using the library()
function.
library(dplyr)
library(tidyverse)
library(tidyr)
We can use the select() function to select specific
columns from the dataframe. When using these functions, the first
argument will always be the name of the dataframe you’re working with,
followed by the name(s) of the column or columns you want to select.
Select one column:
select(dat, age)
Select multiple columns:
select(dat, country, age, sex)
Note in the examples above that none of the operations we just
performed resulted in a new object in the Environment.
This is because we did not use the <- operator to assign
the operations to a new object.
We use the filter() function to filter rows based on
specific criteria. Again, the first argument will be the name of the
dataframe, and the second argument will be the condition that we want
use to filter the data.
Notice that we use a == sign for setting the filter
condition. You can read this as “choose the rows in dat
where country is equal to nigeria.”
filter(dat, country=="nigeria")
We can filter on multiple conditions by using a “,” to
state different conditions.
# Filter all rows for Female in Nigeria
filter(dat, country=="nigeria", sex=="F")
We can also set more complex conditions. By default, each of the
conditions in filter must be TRUE to remain in the filtered
dataframe. But we can also define conditions for AND
(&) and OR (|) options.
# Filter for country Nigeria OR Benin
filter(dat, country=="nigeria" | country=="benin")
# Filter for sex is male AND age is greater than 40
filter(dat, sex=="M" & age > 40)
Another useful operator is the Match operator
%in%, which will return values that match any value in a
list of possible options:
filter(dat, country %in% c("uganda", "benin", "nigeria"))
Finally, we can use the ! operator to specify conditions
that should be excluded.
# To exclude Benin
filter(dat, country != "benin")
The lubridate package provides functions that make
working with dates easier. This package is not included in the
tidyverse so we have to install and load it separately.
# Only do this once
install.packages("lubridate")
library(lubridate)
Let’s create a vector of dates to practice using the
lubridate package.
dates <- c("2021-11-12", "2021-11-16", "2021-11-17")
Right now, R recognizes these as character strings, not dates.
class(dates)
## [1] "character"
We can use the ymd() function from
lubridate to convert them to dates.
dates <- ymd(dates)
class(dates)
## [1] "Date"
lubridate also has functions to extract date parts
(years, months).
year(dates)
## [1] 2021 2021 2021
month(dates)
## [1] 11 11 11
Another common task is to create new columns based on values in
existing columns. The dplyr package that we loaded earlier
has a function to create new columns. The function is
mutate().
First, we can create a simple new column of just one value. To save
the changes to our dataframe, we will use the <-
assignment operator to make sure the new column is added to
dat.
dat <- mutate(dat, new_column=1)
We can also use mathematical operations to create new
columns.
dat <- mutate(dat, half_age=age/2)
Now if we look at our dataframe, we can see that the new columns
have been added at the bottom.
str(dat)
## tibble [49 × 16] (S3: tbl_df/tbl/data.frame)
## $ today : POSIXct[1:49], format: "2023-05-24" "2023-05-24" ...
## $ consent : chr [1:49] "yes" "yes" "yes" "yes" ...
## $ country : chr [1:49] "uganda" "benin" "cotedivoire" "nigeria" ...
## $ sex : chr [1:49] "F" "M" "M" "M" ...
## $ age : num [1:49] 55 28 38 30 35 25 33 31 30 53 ...
## $ occupation : num [1:49] 7 7 2 1 5 5 9 9 9 7 ...
## $ specify_occupation : chr [1:49] NA NA NA NA ...
## $ qualifications : num [1:49] 4 4 4 4 4 4 4 4 3 4 ...
## $ year_graduate : num [1:49] 1997 2016 2018 2016 2013 ...
## $ years_experience : num [1:49] 26 7 5 7 11 3 11 6 2 32 ...
## $ average_hours_day : num [1:49] 8 9 24 8 8 10 8 10 10 6 ...
## $ current_diagnose_treat_rdts : num [1:49] 1 1 1 1 1 1 1 1 1 1 ...
## $ rdt_false_negative : chr [1:49] "no" "yes" "no" "no" ...
## $ specify_treat_negative_rdt_no: chr [1:49] NA "You can't treat patient with a negative results" "Examine the person" "Because the result shows negative so I will go for further investigation" ...
## $ new_column : num [1:49] 1 1 1 1 1 1 1 1 1 1 ...
## $ half_age : num [1:49] 27.5 14 19 15 17.5 12.5 16.5 15.5 15 26.5 ...
In addition to creating new columns, we can rename our existing
columns using the rename() function. For example, we could
rename the today field to be date.
dat <- rename(dat, date=today)
What if we want to select and filter your data at the same time? There are a few ways to do this, including intermediate steps, nested functions, and pipes.
For intermediate steps, we create a new intermediate object for the output of our first function, then use it as the input for our second function. Keep in mind when creating new objects, it is good to use names that are descriptive and concise.
In this example, our task is to create a new data frame that includes only data for Uganda, and only the columns for country, sex, and age:
# Filter the data
dat_uganda_F <- filter(dat, country=="uganda", sex=="F")
# Select the columns of interest
dat_uganda_F_age <- select(dat_uganda_F, country, sex, age)
dat_uganda_F_age
This intermediate steps approach works, however it can clutter your workspace with objects, and uses additional memory.
Another option is to use nested functions but putting one function inside another.
dat_uganda_F_age <- select(filter(dat, country=="uganda", sex=="F"), country, sex, age)
This approach doesn’t clutter the workspace, but it can be tedious to read.
The last option is to use pipes, which allow you to take the output from one function and input it directly into the next function. It is useful for stringing together data cleaning steps while maintaining the readability of your code.
The pipe function of the tidyverse is
%>%. The shortcut to type this symbol is
Ctrl+Shift+M if you use Windows. On Mac the shortcut is
Cmd+Shift+M.
To re-run our previous example using pipes:
dat_uganda_F_age <- dat %>%
filter(country=="uganda", sex=="F") %>%
select(country, sex, age)
Another common data manipulation task involves grouping data together and applying summary functions such as calculating means or totals. We can do some of these types of operations already. For example, we can determine the mean years of experience of HCWs in Nigeria by filtering our data and then calculating the mean:
dat_nigeria <- dat %>%
filter(country=="nigeria")
mean(dat_nigeria$years_experience)
## [1] 8.85
But what if we want to calculate the mean years of experience for all
countries at the same time? We can use the functions
group_by() and summarise() from the
dplyr package.
First, group_by() groups the data by the categories in a
categorical column, then summarise() calculates summary
statistics.
dat %>%
group_by(country) %>%
summarise(mean_years_experience = mean(years_experience))
We can also group by more than one column, and generate more than one summary statistic:
dat %>%
group_by(country, sex) %>%
summarise(mean_years_experience = mean(years_experience),
mean_age = mean(age))
There are many approaches and packages for creating data
visualizations in R. Today we will focus on the package
ggplot2, which is part of the tidyverse
umbrella package.
Visualizations in ggplot2 are built layer by layer. The general structure looks like this:
ggplot(data = <DATA>,
mapping = aes(<MAPPING>))+
<GEOM_FUNCTION>()
ggplot2 visualizations use different geoms
to determine the type of plot. Some common geoms are:
geom_point() for scatter plotsgeom_boxplot() for boxplotsgeom_line() for trend lines, time series plots,
etc.geom_col() for bar plotsLet’s start by creating a simple scatter plot.
ggplot(data = dat,
mapping = aes(x = average_hours_day, y=years_experience))+
geom_point()
We can add more detail to this plot by specifying features in the
aes() function. Different features can be specified in each
layer of the ggplot.
For example, we can color all the points of our plot according to country:
ggplot(data = dat,
mapping = aes(x = average_hours_day, y=years_experience))+
geom_point(aes(color=country))
We can also create a line chart looking at the number of records collected by day. To do this, we will first summarize the data by number of records per day, and then plot:
# Summarise data
records_per_day <- dat %>%
group_by(date) %>%
summarise(count=n())
# Plot
ggplot(data = records_per_day,
mapping = aes(x=date, y=count))+
geom_line()
Next, we can visualize the same data in a bar plot. And because
ggplot2 is part of the tidyverse umbrella of
packages, we can combine the data summary steps into the same command as
the plotting by using pipes! This keeps our workspace declutterd and
uses less memory.
ggplot(data = dat %>%
group_by(date) %>%
summarise(count=n()),
mapping = aes(x=date, y=count))+
geom_col()
Let’s create another bar plot looking at the number of records per country, by male and female HCWs. Again, we will summarise the data in the same step as plotting.
ggplot(data = dat %>%
group_by(country, sex) %>%
summarise(count=n()),
mapping = aes(x=country, y=count))+
geom_col(aes(fill=sex))
There are many options for polishing our plots. In the example below, we rename the axes, arrange the plot in ascending order, and use built in themes to clean up the background of the plot.
ggplot(data = dat %>%
group_by(country, sex) %>%
summarise(count=n()),
mapping = aes(x=reorder(country, count), y=count))+
geom_col(aes(fill=sex))+
labs(x="Country",
y="Number of records",
title="Number of records per country")+
theme_classic()
There are again many approaches to exporting our plots. Today we will
use the ggsave() function. First we have to save our plot
into a new object, and then define the output file path. In this case,
we have already created a plots folder in our R Project
directory where we can save this plot.
# Assign the plot to an object
stacked_bar_plot <- ggplot(data = dat %>%
group_by(country, sex) %>%
summarise(count=n()),
mapping = aes(x=reorder(country, count), y=count))+
geom_col(aes(fill=sex))+
labs(x="Country",
y="Number of records",
title="Number of records per country")+
theme_classic()
# Export the object using ggsave
ggsave(filename="plots/records_per_country.png",
plot=stacked_bar_plot)
Hopefully this orientation has provided you with an introduction to R that will propel you toward further building your R skills. Below is a compilation of free resources, including interactive and self-paced tutorials, that we encourage you to refer to:
result <- rsconnect::rpubsUpload(title="MaCRA R Orientation",
contentFile="MaCRA-R-Orientation_en.html",
originalDoc="Macra-R-Orientation_en.Rmd")
if (!is.null(result$continueUrl))
browseURL(result$continueUrl)
else
stop(result$error)
# Share link: http://rpubs.com/ehilton/MaCRA_R_Orientation_EN