or
or
By clicking below, you agree to our terms of service.
New to HackMD? Sign up
Syntax | Example | Reference | |
---|---|---|---|
# Header | Header | 基本排版 | |
- Unordered List |
|
||
1. Ordered List |
|
||
- [ ] Todo List |
|
||
> Blockquote | Blockquote |
||
**Bold font** | Bold font | ||
*Italics font* | Italics font | ||
~~Strikethrough~~ | |||
19^th^ | 19th | ||
H~2~O | H2O | ||
++Inserted text++ | Inserted text | ||
==Marked text== | Marked text | ||
[link text](https:// "title") | Link | ||
 | Image | ||
`Code` | Code |
在筆記中貼入程式碼 | |
```javascript var i = 0; ``` |
|
||
:smile: | ![]() |
Emoji list | |
{%youtube youtube_id %} | Externals | ||
$L^aT_eX$ | LaTeX | ||
:::info This is a alert area. ::: |
This is a alert area. |
On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?
Please give us some advice and help us improve HackMD.
Do you want to remove this version name and description?
Syncing
xxxxxxxxxx
Workshop Details
Dates: September 6th - 13th, 2022
Time: 9am - 12pm
Workshop Agenda:
https://ucsdlib.github.io/2022-09-06-carpentries-uc/
Lesson:
https://swcarpentry.github.io/r-novice-gapminder/
Day 1 - 3: Introduction to R
Software Installation:
This is an online interface that can be used when unable to download R Studio
Lesson Data (download)
Gapminder data
Feline-data
Gapminder Wide data
NOTES:
A copy of the instructor live session notes will be made available to participants upon request at the end of the workshop.
Workshop Day 1 (83)
First name and Last Name/Organization/Dept./Email
Day 1 Questions:
Please enter any questions not answered during live session here:
1.
End Day 1
Workshop Day 2
First name and Last Name/Organization/Dept./Email
Day 2 Shared Notes
Subsetting Data
We can subset using corresponding indices. To demonstrate this, let's create a simple numeric vector:
#any number would do. You can also assign names to the numeric vectors.
remember
c()
denots for combine or concatenate.To extract a single value, we can use the square bracket
[]
. For example, if we usex[1]
, wherex
is the object of we created and[1]
is the corresponding index.We can use the
c()
and extract multiple elements at once.x[c(1,3)]
would extract first and third elements from the vector.As for the
setwd()
, it is best practice to have the user running the script begin in a consistent directory on their machine and then use relative file paths from that directory to access files.We will be using the
Dplyr and Tidyr
packages that are a part of theTidyverse
package.If. you have not instaleld the
tidyverse
package, you can install it using the following command:NOTE: installing a package needs to be done only once
NOTE: loading library needs to be done every time you run a new R session.
(for more information about the tidyverse, you can visit: https://www.tidyverse.org)
Previously we used
x
for our object name; let's use the same approach and load the.csv
dataset and call the objectgapminder
.Alternative way of loading the dataset:
a new window will pop-up and you can select the file you want to load.
Using the
dplyr
package, we can subset variable names.If you have multiple pacakges loaded, some function share the same name. To avoid any conflict, you may specify the package name.
The
::
tells R console that we want to use a function from a specific package.The pipe operator
%>%
makes the data wrangling process much easier and smoother. The pipe basically means passing down (streaming down) information from one script to the next. Having multiple functions in one command improves the thinking process and improves readability of the script.We can rename an existing variable name:
You can also choose to do all these in one chunk of codes using the %>%
Now we are going to cover the
filter()
function. Previously we covered theselect()
function, which subsets data by the column (variable) names. Thefilter()
function subsets data by rows.Basically, the script above means: take the
gapminder
dataset, subset it byEurope
, and select variablesyear
,country
, andgdpPercap
.By using the pipe operator,
%>%
, we can tell the story of how our data were manipulated.Another example:
Challenge 1
Write a single command (which can span multiple lines and includes pipes) that will produce a data frame that has the African [or any other country you pick] values for lifeExp, country and year, but not for other Continents. How many rows does your data frame have and why?
Instead of using the
filter()
function, which will only pass observations that meet your criteria, we can use thegroup_by()
, which will use every unique criteria that you could have used in filter.Example:
The script above basically states: take the
gapminder
dataset, group values by the variablecontinent
, then summarize values (mean, sd, etc.). The end result should be the mean gdpPercap for each continent.Challenge 2
Calculate the average life expectancy per country. Which has the longest average life expectancy and which has the shortest average life expectancy?
Depends on the research questions, we may use the function
group_by()
to group multiple variables.Sometimes, instead of summarizing informatoin, we want to create a new variable. The
mutate()
function creates a new variable (adds a new column into the dataset).The script above states: take the
gapminder
data, create a new variable calledgdp
which is defined as multiplication betweengdpPercap
andpop
variables.We can extend the script a bit further:
By following the
%>%
operator, we can follow the thinking process of our data manipulation. This improves readability and make the script more reproducible.Day 2 Questions:
Please enter any questions not answered during live session here:
1.
End Day 2
Workshop Day 3
First name and Last Name/Organization/Dept./Email
Day 3 Shared Notes
For when your computer doesn't have admin permissions to install things like packages, RStudio Cloud is a good option
Today we'll be plotting using the
ggplot2
package, which is a popular R plotting packageToday's notes and cheat sheet: https://hackmd.io/3M1KawkLRhezD0u1TAkpfQ?view
ggplot2 cheat sheet
Once
ggplot
is installed, we can call functions from this package by calling theChallenge 1
Part A
In the gapminder example we’ve been using,
use the column “year” to show how life expectancy has changed over time.
Solution:
But this doesn't look great, does it? So, Part B:
Part B
We’ve been using the
aes
function to tell the scatterplot geom about the x and y locations of each point. Another aesthetic property we can modify is the point color. Modify the code from the Part A to color the points by the “continent” column. Is it easier to detect trends?We can use
color
argument inaes()
to specify we want points colored by value ofcontinent
Geom arguments
If we want to use lines rather than a scatterplot, we can use
geom_line()
Instead of adding a geom_point layer, we’ve added a geom_line layer.
However, the result doesn’t look quite as we might have expected: it seems to be jumping around a lot in each continent. Let’s try to separate the data by country, plotting one line for each country:
Note the
by =
additional portionWe’ve added the by aesthetic, which tells ggplot to draw a line for each country.
But what if we want to visualize both lines and points on the plot? We can add another layer to the plot:
It’s important to note that each layer is drawn on top of the previous layer. In this example, the points have been drawn on top of the lines. Here’s a demonstration:
The items within ggplot()
aes()
apply to the entire plot, but can override withaes()
command in individualgeom()
Challenge 2
Switch the order of the point and line layers from the previous example. What happened?
Now the lines are on top of the points
Transformations and trend lines
We can adjust plots in other ways, including transformations and overlaying statistical models
Returning to a scatterplot:
To change the x axis to a log scale using
scale_x_log10()
:And to change the transparency of the points, since there's lots of overplotting, we can use
alpha
ingeom_point()
:To add a trend line, we can use
geom_smooth()
and specify the type of model (here, a linear model, withmethod = 'lm'
):And can change line thickness using
size
ingeom_smooth()
:Challenge 3
Part A
Modify the color and size of the points on the point layer, but don’t use the aes() function in that layer.
Note the
color = "orange"
andsize = 3
withingeom_point()
Part B
Modify your solution to Part A so that the points are now a different shape and are colored by continent with new trendlines. Hint: The color argument can be used inside the aes() function.
want trend line for each continent:
Multi-panel plots
Subset to only Americas data
Then use
ggplot()
withfacet_wrap()
which lets us facet by variable (in this case, by country variable):This gives us a panel for each country
The
theme()
command lets us specify things like x and y axis text and angles. In this case, we're specifyingaxis.text.x
to say we want the x axis text to be at a 45 degree angle.To modify text:
To clean this figure up for a publication we need to change some of the text elements. The x-axis is too cluttered, and the y axis should read “Life expectancy”, rather than the column name in the data frame.
We can do this by adding a couple of different layers. The theme layer controls the axis text, and overall text size. Labels for the axes, plot title and any legend can be set using the labs function. Legend titles are set using the same names we used in the aes specification. Thus below the color legend title is set using color = "Continent", while the title of a fill legend would be set using fill = "MyTitle".
Exporting the plot:
We want to assign our plot to an object (here naming it
lifeExp_plot
, then use ggsave to export the plot to png (specifying file format in output name, here "lifeExp.png")Here we're specifying we want a png as output, width of 12 cm, height of 10 cm, with dpi (basically, resolution) of 300
Producing reports with knitr
Check the notes for screenshots: https://hackmd.io/3M1KawkLRhezD0u1TAkpfQ?view#Create-Reports-with-knitr
(Fun fact, this document uses markdown! You can see how we're making items bold, or putting in code chunks, by selecting the icon in the top banner between the pencil and the eye, to see the raw markdown on theput on the right.)
Challenge
Question 1
Create a new R Markdown document. Delete all of the R code chunks and write a bit of Markdown (some sections, some italicized text, and an itemized list).
Convert the document to a webpage.
Question 2
Load the ggplot2 package
Read the gapminder data
Create a plot
Day 3 Questions:
Please enter any questions not answered during live session here:
2. (see above - we did cover this)
Other R resources
R graph gallery - https://r-graph-gallery.com/ (specific to ggplot 2 - https://r-graph-gallery.com/ggplot2-package.html)
R markdown cookbook - https://bookdown.org/yihui/rmarkdown-cookbook/
R for Data Science (data viz chapter) - https://r4ds.had.co.nz/data-visualisation.html
End Day 3