Last updated: 2024-09-10
Checks: 7 0
Knit directory: My_Project/
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 166be7f. 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: .Rhistory
Ignored: .Rproj.user/
Untracked files:
Untracked: .Rapp.history
Untracked: .gitignore
Untracked: Stats.Rmd
Untracked: Stats.html
Untracked: data/.DS_Store
Untracked: data/COADREAD.clin.merged.picked.txt
Untracked: data/COADREAD.rnaseqv2__illuminahiseq_rnaseqv2__unc_edu__Level_3__RSEM_genes_normalized__data.data.txt
Unstaged changes:
Modified: .DS_Store
Modified: analysis/.DS_Store
Deleted: myproject.zip
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 |
---|---|---|---|---|
html | c3ff74c | oliverdesousa | 2024-09-10 | Build site. |
Rmd | b77ee0a | oliverdesousa | 2024-09-06 | Files |
html | b77ee0a | oliverdesousa | 2024-09-06 | Files |
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
Variable Assignment:
# Variable Assignment
x <- 10
y <- 20
z <- x + y # x & y are now saved in your environment for reuse
Data Types: - Numeric, Character, Boolean, Integer, and Double
# 6 = numeric
# "c" = character
# -5 = integer
# TRUE = boolean
Data Formats:
vectors,
lists,
data frames
# Vectors = arrays of data elements each of the SAME TYPE.
vec <- c(1, 2, 3, 4, 5)
# Lists = can contain many items that (can have different types of data like numbers characters and also could contain stored vectors or data frames.)
lst <- list(name = "John", age = 25)
# Data Frames = tabular (2-dimensional) data structure that can store values of any data type.
df <- data.frame(Name = c("Alice", "Bob"), Age = c(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
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: 0x1196adf28>
<environment: namespace:ggplot2>
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.
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
# Select 2nd column:
second_column <- df[, 2] # Selects the entire second column ('abb')
# Select the element in the 3rd row and 4th column:
specific_element <- df[3, 4] # Selects the population ('pop') of the third city ('Lagos')
Indexing Using COLUMN Names:
# Select the 'city' column:
city_column <- df$city # Selects the 'city' column
# 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
# Logical Indexing:
large_cities <- df[df$pop > 10000000, ] # Returns all rows where 'pop' is greater than 10 million
Indexing with dplyr
:
# Using dplyr you can perform similar operations with clearer syntax:
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
# Select specific columns
selected_df <- df %>%
select(city, pop) # Selects 'city' and 'pop' columns
# Filter rows based on a condition
filtered_df <- df %>%
filter(pop > 10000000) # Filters for cities with population greater than 10 million
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")
)
# Creating a Matrix
matrix_example <- matrix(1:9, nrow = 3, byrow = TRUE)
# Creating a List
list_example <- list(
numbers = 1:5,
text = c("A", "B", "C"),
data_frame = df
)
# Extract cities with population greater than 10 million
large_cities <- df[df$population > 10000000, ]
# Extract cities in the 'South' region
south_cities <- df[df$region == "South", ]
# Select Specific Columns
city_population <- df[, c("city", "population")]
# Add a New Column: City Area (dummy data)
df$area <- c(606, 851, 1171, 300, 400) # Example areas in square kilometers
# Modify Existing Column: Increase Population by 10%
df$population <- df$population * 1.10
# 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)
Exercise: :
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.4.1 (2024-06-14)
Platform: aarch64-apple-darwin20
Running under: macOS Sonoma 14.6.1
Matrix products: default
BLAS: /Library/Frameworks/R.framework/Versions/4.4-arm64/Resources/lib/libRblas.0.dylib
LAPACK: /Library/Frameworks/R.framework/Versions/4.4-arm64/Resources/lib/libRlapack.dylib; LAPACK version 3.12.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
loaded via a namespace (and not attached):
[1] gtable_0.3.5 jsonlite_1.8.8 compiler_4.4.1 promises_1.3.0
[5] tidyselect_1.2.1 Rcpp_1.0.13 stringr_1.5.1 git2r_0.33.0
[9] later_1.3.2 jquerylib_0.1.4 scales_1.3.0 yaml_2.3.10
[13] fastmap_1.2.0 R6_2.5.1 generics_0.1.3 workflowr_1.7.1
[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.47
[29] fs_1.6.4 sass_0.4.9 cli_3.6.3 withr_3.0.1
[33] magrittr_2.0.3 digest_0.6.37 grid_4.4.1 rstudioapi_0.16.0
[37] lifecycle_1.0.4 vctrs_0.6.5 evaluate_0.24.0 glue_1.7.0
[41] whisker_0.4.1 colorspace_2.1-1 fansi_1.0.6 rmarkdown_2.28
[45] tools_4.4.1 pkgconfig_2.0.3 htmltools_0.5.8.1