# <, >, ==, <=, >=, !=
1 > 2
1 <= 2
x <- 1:9
x > 5
iris$Sepal.Length > 4
iris$Species == "versicolor"
iris$Sepal.Length[iris$Species == "versicolor"]
# & ! |
1 < 2 & 3 > 4
1 < 2 | 3 > 4
! 1 < 2
# maths
TRUE + TRUE
TRUE + FALSE
TRUE * FALSE
TRUE / FALSE
FALSE / TRUE
sum(c(TRUE, FALSE, TRUE))
sum(iris$Species == "versicolor")ENV221 L03
1 Overview of the module and R
2 R Basic Operations
3 R Programming
3.1 Learning objectives
In this lecture, you will learn
- the basic flow works of programming,
- the R functions for conditional statements,
- the R functions for loop,
- the fundamental knowledge of R packages, and
- how to find useful R packages for researches on environmental science.
3.2 Conditional statements
3.2.1 Logical operations
Action: What does && and || mean?
3.2.2 if () {}
hour <- 12
if (hour == 12) {
print('Time for lunch. Go!')
}3.2.3 if () {} else {}
hour <- 12
if(hour < 12) {
print('Good morning.')
} else {
print('Good afternoon.')
}3.2.4 ifelse()
iris$long_sepal <- ifelse(
iris$Sepal.Length > mean(iris$Sepal.Length),
'long',
'short')
iris$big <- ifelse(
iris$Sepal.Length > mean(iris$Sepal.Length) & iris$Sepal.Width > mean(iris$Sepal.Width),
'big',
'small')Demonstration: Add a new column to the Air Quality dataset, showing the months in English.
3.3 Loop
3.3.1 for () {}
x <- 1:10
# repeat the same work
for(i in x){
print('Hello World!')
}
# different work
for(i in x){
print(i)
}Demonstration:
Suppose the concentration of ambient CO2 is 400 ppm this year. It increases by 1% every year. What will it be after 50 years?
x <- 400
for (i in 1:50){
x <- x + 0.01 * x
}
x
400 * (1.01 ^ 50)Demonstration: Create multiple folders.
dir.create("test")
x <- letters[1:7]
for(i in x){
dir.create(i)
}3.3.2 while () {}
Demonstration:
Suppose the concentration of ambient CO2 is 400 ppm this year. It increases by 1% every year. After how many years will it reach 1000 ppm?
x <- 400
r <- 0.01
year <- 0
while(x < 1000){
year <- year + 1
x <- x + x * r
}
year3.3.3 repeat()
repeat print(1)Demonstration:
\(x = 1 + 2 + 3 + ... + n\). What it the smallest value of \(n\) when \(x\) > 10000?
sum <- 0
n <- 1
repeat{
sum <- sum + n
n <- n + 1
if (sum > 10000){
break
}
}
nAction: Rewrite these codes using the while () {} function.
3.4 Functions
3.4.1 Structure
A function is a cooking machine:
# Common form:
mean(1:10)
plot(iris$Sepal.Length, iris$Sepal.Width)
# Complete form:
mean(x = 1:10)
plot(x = iris$Sepal.Length, y = iris$Sepal.Width)
plot(y = iris$Sepal.Width, x = iris$Sepal.Length)3.4.2 Help
help(mean)
?mean
# F1
mean(x, trim = 0, na.rm = FALSE, ...)Action: What is the complete form for the function read.csv() and write.csv()? Explain each argument.
3.4.3 User-defined functions
function_name <- function(argument_1, argument2, ...)Convert Wind from mph (mile per hour) to m/s (meter per second):
\[v_\text {ms} = v_\text{mph} \times 1.609344 \times 1000 / 3600\]
# Define the function:
convert_windspeed <- function(x){
y <- x * 1.609344 * 1000 / 3600
return(y)
}
# Use the function:
convert_windspeed(x = 1)
# A short one:
convert_windspeed <- function(x){
x * 1.609344 * 1000 / 3600
}
# A little more complicated:
convert_windspeed2 <- function(x, unit = "m/s"){
if (unit == "m/s"){
y <- x * 1.609344 * 1000 / 3600
}
if (unit == "km/hour"){
y <- x * 1.609344
}
return(y)
}
convert_windspeed2(1, "km/hour")Question: What if the user misspell the unit, such as unit = "ms"?
3.5 R packages
A function is a cooking machine.
An R package is a kitchen with one or more cooking machines.
- MatLab: toolboxes
- python: libraries
- MS Office: modules
- Chrome: add-ons/plugins
- R: packages. Over 16,000 packages on CRAN + countless packages on GitHub + …
Number of R packages published on CRAN (Image source)
3.6 Install packages
3.6.1 From CRAN
Something like peer reviewed:
install.packages(ggplot2)
install.packages(remotes)3.6.2 From github
Something like grey papers or self-published:
library(remotes)
install_github("pzhaonet/beginr")3.6.3 From local files
- Download a package archive file
- RStudio -> Tools -> Install packages –> Package Archive File
3.6.4 Where are they installed
Check the installation path:
.libPaths()3.7 Load a package
library()
require()
beginr::plotpch()Question: What is the difference between library() and require()?
3.8 Overview a package
3.8.1 What is it used for
help()
help(package = "beginr")
help(package = "plotrix")
demo()
demo(plotrix)
vignette()
vignette(datatable-intro)3.8.2 How popular is it
beginr::plotpkg("plotrix")
beginr::plotpkg("ggplot2")3.8.3 What is the usage of a function in it
help(topic = plotpkg, package = "beginr")
library(beginr)
help("plotpkg")
library(ggplot2)
example(qplot)3.8.4 What data does it have
data()3.8.5 Who develop(s) it
citation() # search the authors3.9 Find and choose packages
- Task view: https://cran.r-project.org/web/views/
- Search engine
- Reputation
- References in literature
- CRAN Explorer: https://nz-stefan.shinyapps.io/cran-explorer/
3.10 Further readings
- (Optional) R packages