Last updated: 2024-09-05
Checks: 7 0
Knit directory: Tutorials/
This reproducible R Markdown analysis was created with workflowr (version 1.7.1). The Checks tab describes the reproducibility checks that were applied when the results were created. The Past versions tab lists the development history.
Great! Since the R Markdown file has been committed to the Git repository, you know the exact version of the code that produced these results.
Great job! The global environment was empty. Objects defined in the global environment can affect the analysis in your R Markdown file in unknown ways. For reproduciblity it’s best to always run the code in an empty environment.
The command set.seed(20240905)
was run prior to running
the code in the R Markdown file. Setting a seed ensures that any results
that rely on randomness, e.g. subsampling or permutations, are
reproducible.
Great job! Recording the operating system, R version, and package versions is critical for reproducibility.
Nice! There were no cached chunks for this analysis, so you can be confident that you successfully produced the results during this run.
Great job! Using relative paths to the files within your workflowr project makes it easier to run your code on other machines.
Great! You are using Git for version control. Tracking code development and connecting the code version to the results is critical for reproducibility.
The results in this page were generated with repository version dbbf64a. See the Past versions tab to see a history of the changes made to the R Markdown and HTML files.
Note that you need to be careful to ensure that all relevant files for
the analysis have been committed to Git prior to generating the results
(you can use wflow_publish
or
wflow_git_commit
). workflowr only checks the R Markdown
file, but you know if there are other scripts or data files that it
depends on. Below is the status of the Git repository when the results
were generated:
Ignored files:
Ignored: .DS_Store
Note that any generated files, e.g. HTML, png, CSS, etc., are not included in this status report because it is ok for generated content to have uncommitted changes.
These are the previous versions of the repository in which changes were
made to the R Markdown (analysis/Module_1_Basics.Rmd
) and
HTML (docs/Module_1_Basics.html
) files. If you’ve
configured a remote Git repository (see ?wflow_git_remote
),
click on the hyperlinks in the table below to view the files as they
were in that past version.
File | Version | Author | Date | Message |
---|---|---|---|---|
Rmd | 8486be7 | tkcaccia | 2024-09-05 | update |
Open RStudio and take a few minutes to explore each pane and its functionality.
In this section, we’ll get to know the RStudio interface and understand its different components:
Layout: The RStudio interface consists of several panes that help you manage your workflow efficiently.
Panes: These include the Source Pane, Console, Environment/History Pane, and the Files/Plots/Packages/Help/Viewer Pane.
Console: The Console is where you can directly execute R commands.
Script Editor: The Script Editor is used for writing and editing scripts, which can be executed in parts or as a whole.
Environment: The Environment Pane shows all the objects (data, functions, etc.) that you’ve created during your session.
Let’s start by performing some basic operations in R:
Arithmetic:
# Basic Arithmetic
sum <- 5 + 3
difference <- 5 - 3
product <- 5 * 3
quotient <- 5 / 3
exponent <- 5 ^ 3
modulus <- 5 %% 3 # Remainder from division
int_division <-5 %/% 3 # Integer Division
# Display results
sum
[1] 8
difference
[1] 2
product
[1] 15
quotient
[1] 1.666667
exponent
[1] 125
modulus
[1] 2
int_division
[1] 1
Variable Assignment:
# Variable Assignment
x <- 10
y <- 20
z <- x + y # x & y are now saved in your environment for reuse
z
[1] 30
Data Types: - Include Numeric, Character, Boolean, Integer, and Double types of data.
n <- numeric(6)
typeof(n) # a function used to return the type of the data stored
[1] "double"
c <- "c"
typeof(c)
[1] "character"
# Integer values are whole numbers that can be positive or negative
i <- integer(5)
typeof(i)
[1] "integer"
# Boolean Values consists of data hat has one of two values (e.g., 1 or 0 / True or False)
t <- TRUE # can store as letter "T"
f <- FALSE # can store as letter "F"
typeof(t)
[1] "logical"
typeof(f) # logical = boolean
[1] "logical"
Data Formats:
vectors,
lists,
data frames
# Vectors are arrays of data elements each of the SAME TYPE.
vec <- c(1, 2, 3, 4, 5)
# Lists contain multiple items that can be of different data types like numbers characters and also could contain stored vectors or data frames.
lst <- list(name = "John", age = 25)
# Data Frames are a tabular (2-dimensional) data structure that can store values of any data type.
df <- data.frame(Name = c("Alice", "Bob"), Age = c(25, 30))
vec
[1] 1 2 3 4 5
lst
$name
[1] "John"
$age
[1] 25
df
Name Age
1 Alice 25
2 Bob 30
Exercise 1: Try creating your own variables and performing different operations. Experiment with different data types.
Exercise 2: Use
the function str(x)
to check the structure of each data
type.
str(vec)
num [1:5] 1 2 3 4 5
str(lst)
List of 2
$ name: chr "John"
$ age : num 25
str(df)
'data.frame': 2 obs. of 2 variables:
$ Name: chr "Alice" "Bob"
$ Age : num 25 30
Understanding and creating functions is fundamental in R:
Creating Simple Functions: Here’s how you can create a simple function in R.
# Creating a Function
add_numbers <- function(a, b) {
return(a + b) # takes two arguments (a and b) and returns their sum.
}
# Using the Function: Here we are calling the function 'add_numbers' with 10 and 15 as inputs.
add_numbers(10, 15)
[1] 25
Exercise 3: Create a function that takes a number as input and returns the square of that number.
sq <- function(n1,n2) {
first_step <- n1 + n2
return(first_step^2) # also can use the function sqrt(first_step)
}
sq(2,3)
[1] 25
R packages are collections of functions and datasets developed by the R community:
There are pre-loaded packages in Rstudio that can be used and called without installation (e.g., dplyr)
CRAN: CRAN (Comprehensive R Archive Network) is the main repository for R packages.
Installing and Loading Packages: To use additional functions, you might need to install and load packages.
# Installing a Package (Uncomment the line below if the package has been loaded previously)
# install.packages("ggplot2")
# Loading the package "ggplot" a data visualtion package we will use later in the course:
library(ggplot2) # no quotations needed when loading a package from your library
ggplot
function (data = NULL, mapping = aes(), ..., environment = parent.frame())
{
UseMethod("ggplot")
}
<bytecode: 0x1147aa0b0>
<environment: namespace:ggplot2>
Exercise 4: Install and load the dplyr package. Use it to manipulate a data frame of your choice.
Hint use the code
browseVignettes(package = "dplyr")
to see how you could use
this package.
# install.packages("dplyr")
# ?dplyr
# browseVignettes(package = "dplyr") --> see what you can do with dplyr
library(dplyr)
Attaching package: 'dplyr'
The following objects are masked from 'package:stats':
filter, lag
The following objects are masked from 'package:base':
intersect, setdiff, setequal, union
# Manipulating data:
data <- data.frame(
Name = c("Alice", "Bob", "Charlie", "David", "Eva"), # Example data frame
Age = c(23, 35, 45, 29, 31),
Score = c(89, 72, 95, 88, 76)
)
# 1. Select specific columns (Name and Score)
selected_data <- data %>%
select(Name, Score)
# 2. Filter rows where Age is greater than 30
filtered_data <- data %>%
filter(Age > 30)
# 3. Arrange the data by Score in descending order
arranged_data <- data %>%
arrange(desc(Score))
[1] "Selected Data:"
Name Score
1 Alice 89
2 Bob 72
3 Charlie 95
4 David 88
5 Eva 76
[1] "Filtered Data (Age > 30):"
Name Age Score
1 Bob 35 72
2 Charlie 45 95
3 Eva 31 76
[1] "Arranged Data by Score (Descending):"
Name Age Score
1 Charlie 45 95
2 Alice 23 89
3 David 29 88
4 Eva 31 76
5 Bob 35 72
Data analysis often involves importing data from external files:
R can read data from various formats like CSV, Excel, etc.
It is important to pay attention to the extension the file uses (e.g., csv = comman seperated values)
# Reading CSV Files:
# df_csv <- read.csv("path/to/your/file.csv")
# Reading Excel Files (requires the readxl package)
# install.packages("readxl)
# library(readxl)
# df_excel <- read_excel("path/to/your/file.xlsx")
TIP: If you look at the top left of Rstudio you can import the dataset manually using the “Import Dataset” option.
Exercise 5: Try reading a sample CSV file into R. Practice using different data formats if available.
# df_csv <- read.csv("path/to/sample/file/sample.csv", sep = ",")
# df_table <- read.table("path/to/sample/file/sample.tsv, sep = "\t"")
# df_table <- read.excel("path/to/sample/file/sample.xlsx)
# If file is a text (.txt) file, remember to check what the extension is before reading it in.
df <- data.frame(city, abb, region, pop, total)
head(df) # shows the first 'n' rows
city abb region pop total
1 Cairo CA North 22183200 125700
2 Kinshasa KI Central 16315534 80500
3 Lagos LA Central 15387639 66900
4 Luanda LU South 8952496 51700
5 Dar es Salaam DS South 7404689 36400
6 Khartoum KH North 6160327 45700
Indexing ROWS and COLUMNS by POSITION:
# Select 1st Row:
first_row <- df[1, ] # Selects the entire first row
first_row
city abb region pop total
1 Cairo CA North 22183200 125700
# Select 2nd column:
second_column <- df[, 2] # Selects the entire second column ('abb')
second_column
[1] "CA" "KI" "LA" "LU" "DS" "KH" "JO" "AB" "AD" "NA" "YA" "CB" "AN" "KA" "KU"
[16] "DA" "OU" "LS" "AL" "BA" "BR" "MO" "TU" "CO" "LO" "MA" "MN" "HA" "ND" "NO"
[31] "NI" "FR" "LI" "KG" "AC" "TR" "BU" "AS" "BG" "LB"
# Select the element in the 3rd row and 4th column:
specific_element <- df[3, 4] # Selects the population ('pop') of the third city ('Lagos')
specific_element
[1] 15387639
Indexing Using COLUMN Names:
# Select the 'city' column:
city_column <- df$city # Selects the 'city' column
city_column
[1] "Cairo" "Kinshasa" "Lagos" "Luanda"
[5] "Dar es Salaam" "Khartoum" "Johannesburg" "Abidjan"
[9] "Addis Ababa" "Nairobi" "Yaoundé" "Casablanca"
[13] "Antananarivo" "Kampala" "Kumasi" "Dakar"
[17] "Ouagadougou" "Lusaka" "Algiers" "Bamako"
[21] "Brazzaville" "Mogadishu" "Tunis" "Conakry"
[25] "Lomé" "Matola" "Monrovia" "Harare"
[29] "N'Djamena" "Nouakchott" "Niamey" "Freetown"
[33] "Lilongwe" "Kigali" "Abomey-Calavi" "Tripoli"
[37] "Bujumbura" "Asmara" "Bangui" "Libreville"
# Select the first row using column names:
first_row_city_pop <- df[1, c("city", "pop")] # Selects the 'city' and 'pop' columns for the first row
first_row_city_pop
city pop
1 Cairo 22183200
# Logical Indexing:
large_cities <- df[df$pop > 10000000, ] # Returns all rows where 'pop' is greater than 10 million
large_cities
city abb region pop total
1 Cairo CA North 22183200 125700
2 Kinshasa KI Central 16315534 80500
3 Lagos LA Central 15387639 66900
Indexing with dplyr
:
# Using dplyr you can perform similar operations with clearer syntax:
library(dplyr)
# Select specific columns
selected_df <- df %>%
select(city, pop) # Selects 'city' and 'pop' columns
selected_df
city pop
1 Cairo 22183200
2 Kinshasa 16315534
3 Lagos 15387639
4 Luanda 8952496
5 Dar es Salaam 7404689
6 Khartoum 6160327
7 Johannesburg 6065354
8 Abidjan 5515790
9 Addis Ababa 5227794
10 Nairobi 5118844
11 Yaoundé 4336670
12 Casablanca 3840396
13 Antananarivo 3699900
14 Kampala 3651919
15 Kumasi 3630326
16 Dakar 3326001
17 Ouagadougou 3055788
18 Lusaka 3041789
19 Algiers 2853959
20 Bamako 2816943
21 Brazzaville 2552813
22 Mogadishu 2497463
23 Tunis 2435961
24 Conakry 2048525
25 Lomé 1925517
26 Matola 1796872
27 Monrovia 1622582
28 Harare 1557740
29 N'Djamena 1532588
30 Nouakchott 1431539
31 Niamey 1383909
32 Freetown 1272145
33 Lilongwe 1222325
34 Kigali 1208296
35 Abomey-Calavi 1188736
36 Tripoli 1175830
37 Bujumbura 1139265
38 Asmara 1034872
39 Bangui 933176
40 Libreville 856854
# Filter rows based on a condition
filtered_df <- df %>%
filter(pop > 10000000) # Filters for cities with population greater than 10 million
filtered_df
city abb region pop total
1 Cairo CA North 22183200 125700
2 Kinshasa KI Central 16315534 80500
3 Lagos LA Central 15387639 66900
Exercise 6: Given the following dataframe
df <- data.frame(
city = c("Cairo", "Kinshasa", "Lagos", "Luanda", "Dar es Salaam"),
abb = c("CA", "KI", "LA", "LU", "DS"),
region = factor(c("North", "Central", "Central", "South", "South"),
levels = c("North", "Central", "South")),
pop = c(22183200, 16315534, 15387639, 8952496, 7404689),
total = c(125700, 80500, 66900, 51700, 36400)
)
head(df)
city abb region pop total
1 Cairo CA North 22183200 125700
2 Kinshasa KI Central 16315534 80500
3 Lagos LA Central 15387639 66900
4 Luanda LU South 8952496 51700
5 Dar es Salaam DS South 7404689 36400
a. Select the Population of the First City (Cairo):
b. Select the Abbreviation for the Third City
c. Select the Entire Row for the Fourth City
d. Select the ‘city’ and ‘pop’ Columns for the Second and Fifth Cities
e. Filter for Cities in the ‘South’ Region
f. Using dplyr, Select the city and total Columns
# a. Population of the First City
df[1, "pop"]
[1] 22183200
# b. Abbreviation for the Third City
df[3, "abb"]
[1] "LA"
# c. Entire Row for the Fourth City
df[4, ]
city abb region pop total
4 Luanda LU South 8952496 51700
# d. 'city' and 'pop' Columns for the Second and Fifth Cities
df[c(2, 5), c("city", "pop")]
city pop
2 Kinshasa 16315534
5 Dar es Salaam 7404689
# e. Filter for Cities in the 'South' Region
df[df$region == "South", ]
city abb region pop total
4 Luanda LU South 8952496 51700
5 Dar es Salaam DS South 7404689 36400
# f. Using dplyr, Select the 'city' and 'total' Columns
library(dplyr)
df %>%
select(city, total)
city total
1 Cairo 125700
2 Kinshasa 80500
3 Lagos 66900
4 Luanda 51700
5 Dar es Salaam 36400
Basic data manipulation is key to preparing data for analysis.
Overview of Data Classes: Learn about data frames, matrices, and lists.
Data Frames: Rectangular tables with rows and columns, where columns can be of different types.
Matrices: Rectangular tables with rows and columns, where all elements must be of the same type.
Lists: Collections of elements that can be of different types, including other lists.
# Creating a Data Frame
df <- data.frame(
city = c("Cairo", "Kinshasa", "Lagos", "Luanda", "Dar es Salaam"),
population = c(22183200, 16315534, 15387639, 8952496, 7404689),
region = c("North", "Central", "Central", "South", "South")
)
head(df)
city population region
1 Cairo 22183200 North
2 Kinshasa 16315534 Central
3 Lagos 15387639 Central
4 Luanda 8952496 South
5 Dar es Salaam 7404689 South
# Creating a Matrix
matrix_example <- matrix(1:9, nrow = 3, byrow = TRUE)
head(matrix_example)
[,1] [,2] [,3]
[1,] 1 2 3
[2,] 4 5 6
[3,] 7 8 9
# Creating a List
list_example <- list(
numbers = 1:5,
text = c("A", "B", "C"),
data_frame = df
)
print(list_example)
$numbers
[1] 1 2 3 4 5
$text
[1] "A" "B" "C"
$data_frame
city population region
1 Cairo 22183200 North
2 Kinshasa 16315534 Central
3 Lagos 15387639 Central
4 Luanda 8952496 South
5 Dar es Salaam 7404689 South
# Extract cities with population greater than 10 million
large_cities <- df[df$population > 10000000, ]
print(large_cities)
city population region
1 Cairo 22183200 North
2 Kinshasa 16315534 Central
3 Lagos 15387639 Central
# Extract cities in the 'South' region
south_cities <- df[df$region == "South", ]
print(south_cities)
city population region
4 Luanda 8952496 South
5 Dar es Salaam 7404689 South
# Select Specific Columns
city_population <- df[, c("city", "population")]
print(city_population)
city population
1 Cairo 22183200
2 Kinshasa 16315534
3 Lagos 15387639
4 Luanda 8952496
5 Dar es Salaam 7404689
# Add a New Column: City Area (dummy data)
df$area <- c(606, 851, 1171, 300, 400) # Example areas in square kilometers
print(df)
city population region area
1 Cairo 22183200 North 606
2 Kinshasa 16315534 Central 851
3 Lagos 15387639 Central 1171
4 Luanda 8952496 South 300
5 Dar es Salaam 7404689 South 400
# Modify Existing Column: Increase Population by 10%
df$population <- df$population * 1.10
print(df)
city population region area
1 Cairo 24401520 North 606
2 Kinshasa 17947087 Central 851
3 Lagos 16926403 Central 1171
4 Luanda 9847746 South 300
5 Dar es Salaam 8145158 South 400
# Using dplyr for Data Manipulation:
# Add a New Column: City Area
df <- df %>%
mutate(area = c(606, 851, 1171, 300, 400))
# Modify Existing Column: Increase Population by 10%
df <- df %>%
mutate(population = population * 1.10)
# Filter: Cities in the 'South' Region
south_cities_dplyr <- df %>%
filter(region == "South")
# Select Specific Columns
city_population_dplyr <- df %>%
select(city, population)
print(df)
city population region area
1 Cairo 26841672 North 606
2 Kinshasa 19741796 Central 851
3 Lagos 18619043 Central 1171
4 Luanda 10832520 South 300
5 Dar es Salaam 8959674 South 400
print(south_cities_dplyr)
city population region area
1 Luanda 10832520 South 300
2 Dar es Salaam 8959674 South 400
print(city_population_dplyr)
city population
1 Cairo 26841672
2 Kinshasa 19741796
3 Lagos 18619043
4 Luanda 10832520
5 Dar es Salaam 8959674
Exercise 7:
a. Data Classes: Extract the population of the 3rd city from the df data frame.
b. Subsetting Data -> Extract the elements from matrix_example that are greater than 5.
c. Basic Transformations: Add a new column area to df with values 500, 600, 700, 800, 900.
# 7a:
df[3, "population"]
[1] 18619043
# 7b:
matrix_example[matrix_example > 5]
[1] 7 8 6 9
# 7c:
df$area <- c(500, 600, 700, 800, 900)
head(df)
city population region area
1 Cairo 26841672 North 500
2 Kinshasa 19741796 Central 600
3 Lagos 18619043 Central 700
4 Luanda 10832520 South 800
5 Dar es Salaam 8959674 South 900
sessionInfo()
R version 4.3.3 (2024-02-29)
Platform: aarch64-apple-darwin20 (64-bit)
Running under: macOS Sonoma 14.5
Matrix products: default
BLAS: /Library/Frameworks/R.framework/Versions/4.3-arm64/Resources/lib/libRblas.0.dylib
LAPACK: /Library/Frameworks/R.framework/Versions/4.3-arm64/Resources/lib/libRlapack.dylib; LAPACK version 3.11.0
locale:
[1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8
time zone: Africa/Johannesburg
tzcode source: internal
attached base packages:
[1] stats graphics grDevices utils datasets methods base
other attached packages:
[1] dplyr_1.1.4 ggplot2_3.5.1 workflowr_1.7.1
loaded via a namespace (and not attached):
[1] gtable_0.3.5 jsonlite_1.8.8 compiler_4.3.3 promises_1.3.0
[5] tidyselect_1.2.1 Rcpp_1.0.13 stringr_1.5.1 git2r_0.33.0
[9] callr_3.7.6 later_1.3.2 jquerylib_0.1.4 scales_1.3.0
[13] yaml_2.3.10 fastmap_1.2.0 R6_2.5.1 generics_0.1.3
[17] knitr_1.48 tibble_3.2.1 munsell_0.5.1 rprojroot_2.0.4
[21] bslib_0.8.0 pillar_1.9.0 rlang_1.1.4 utf8_1.2.4
[25] cachem_1.1.0 stringi_1.8.4 httpuv_1.6.15 xfun_0.46
[29] getPass_0.2-4 fs_1.6.4 sass_0.4.9 cli_3.6.3
[33] withr_3.0.1 magrittr_2.0.3 ps_1.7.7 grid_4.3.3
[37] digest_0.6.36 processx_3.8.4 rstudioapi_0.16.0 lifecycle_1.0.4
[41] vctrs_0.6.5 evaluate_0.24.0 glue_1.7.0 whisker_0.4.1
[45] colorspace_2.1-1 fansi_1.0.6 rmarkdown_2.27 httr_1.4.7
[49] tools_4.3.3 pkgconfig_2.0.3 htmltools_0.5.8.1