# <, >, ==, <=, >=, !=
1 > 2
1 <= 2
<- 1:9
x > 5
x $Sepal.Length > 4
iris$Species == "versicolor"
iris$Sepal.Length[iris$Species == "versicolor"]
iris
# & ! |
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 () {}
<- 12
hour if (hour == 12) {
print('Time for lunch. Go!')
}
3.2.3 if () {} else {}
<- 12
hour if(hour < 12) {
print('Good morning.')
else {
} print('Good afternoon.')
}
3.2.4 ifelse()
$long_sepal <- ifelse(
iris$Sepal.Length > mean(iris$Sepal.Length),
iris'long',
'short')
$big <- ifelse(
iris$Sepal.Length > mean(iris$Sepal.Length) & iris$Sepal.Width > mean(iris$Sepal.Width),
iris'big',
'small')
Demonstration: Add a new column to the Air Quality dataset, showing the months in English.
3.3 Loop
3.3.1 for () {}
<- 1:10
x
# 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?
<- 400
x for (i in 1:50){
<- x + 0.01 * x
x
}
x
400 * (1.01 ^ 50)
Demonstration: Create multiple folders.
dir.create("test")
<- letters[1:7]
x 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?
<- 400
x <- 0.01
r <- 0
year while(x < 1000){
<- year + 1
year <- x + x * r
x
} year
3.3.3 repeat()
repeat print(1)
Demonstration:
\(x = 1 + 2 + 3 + ... + n\). What it the smallest value of \(n\) when \(x\) > 10000?
<- 0
sum <- 1
n repeat{
<- sum + n
sum <- n + 1
n if (sum > 10000){
break
}
} n
Action: 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(argument_1, argument2, ...) function_name
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:
<- function(x){
convert_windspeed <- x * 1.609344 * 1000 / 3600
y return(y)
}# Use the function:
convert_windspeed(x = 1)
# A short one:
<- function(x){
convert_windspeed * 1.609344 * 1000 / 3600
x
}
# A little more complicated:
<- function(x, unit = "m/s"){
convert_windspeed2 if (unit == "m/s"){
<- x * 1.609344 * 1000 / 3600
y
}if (unit == "km/hour"){
<- x * 1.609344
y
}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()
::plotpch() beginr
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
::plotpkg("plotrix")
beginr::plotpkg("ggplot2") beginr
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 authors
3.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