TRUE & TRUE
TRUE & FALSE
TRUE | FALSE
!TRUE
2 == 3
5 < 6
c(1,4) >= 6
9 != 8
5 < 6 & 9 != 8
score <- 80
exam_no <- 2
score >= 75 | exam_no == 1
score>=75 & score<90 | exam_no==1
The if statement executes a chunk of code if and only if a defined condition is TRUE, which looks something like this:
if(TRUE) message("It was true!")
## It was true!
if(FALSE) message("It wasn't true!")
if(TRUE&FALSE) message("It was true!")
if(TRUE|FALSE) message("It doesn't matter")
## It doesn't matter
a <- 3
num <- 4
if ( a != num ) {
print(a)
}
## [1] 3
a <- 3
num <- 4
if ( a <= num ) {
a <- a ^ 2
print(a)
}
## [1] 9
num <- -1
if ( num < 0 ) {
print("num is negative.")
print("Don't worry, I'll fix it.")
num <- num * -1
print("Now num is positive.")
}
## [1] "num is negative."
## [1] "Don't worry, I'll fix it."
## [1] "Now num is positive."
num
## [1] 1
Try it
Is it in the range ?
x <- 6
y <- 2
if ( x > 3 & x == 7 ) {
print("It is in the range")
z <- x + y
print(z)
}
Is it in the range ?
x <- 6
y <- 2
if ( x > 3 & x <= 7 ) {
print("It is in the range")
z <- x + y
print(z)
}
## [1] "It is in the range"
## [1] 8
Try it
You have a fruit which is yellow.
Is that a banana?
Or an orange ?
banana <- "yellow"
my_fruit <- "yellow"
if ( my_fruit == banana ) {
print("Your fruit might be a banana")
}
orange <- "orange"
my_fruit <- "yellow"
if ( my_fruit == orange ) {
print("Your fruit is not a banana")
}
If you want something different to happen when the condition is FALSE, you can add an else declaration.
if(FALSE)
{
message("This won't execute...")
} else
{
message("but this will.")
}
## but this will.
a <- 3.5
b <- 0.5
if (a <= 0.5) {
c <- b + 1
print(c)
} else {
c <- b
print(c)
}
## [1] 0.5
Let’s say we have two conditions. Rainy or Shiny.
And you have recorded 4 mm precipitation.
weather <- # mm # fill this number
if ( ) { # fill this condition, using weather
print("it is rainy")
} else {
print("it is shiny")
}
Report the weather. Is it rainy ?
Let’s say we have two conditions. Rainy or Shiny.
And you have recorded 4 mm precipitation.
weather <- 4 # mm # fill this number
if ( weather > 0 ) { # fill this condition, using weather
print("it is rainy")
} else {
print("it is shiny")
}
## [1] "it is rainy"
If your situation has more than two mutually exclusive cases, use else and if statements together.
a <- 1 # team 'a' has 1 goal
b <- 1 # team 'b' has 1 goal
if (a > b) {
print("A wins!")
} else if (a < b) {
print("B wins!")
} else {
print("Tie.")
}
## [1] "Tie."
What do you gonna do ? Eating, Sleeping, or Reading?
When do you want to read ?
So, start to think about your feelings about sleeping or eating to decide whether reading or not.
What do you gonna do ? Eating, Sleeping, or Reading?
Let’s start with define the conditions
If you are hungry –> eat
If you are sleepy –> sleep
What do you gonna do ? Eat, Sleep or Read?
Let’s define your feelings. Yes (TRUE,1) or No (FALSE,0)
hungry <- # TRUE or FALSE (1 or 0)
sleepy <- # TRUE or FALSE (1 or 0)
What do you gonna do ? Eat, Sleep or Read?
hungry <- TRUE # Yes , TRUE , 1
sleepy <- TRUE # Yes , TRUE , 1
if ( ) {
print(" ")
} else if ( ) {
print(" ")
} else if ( ) {
print(" ")
} else {
print(" ")
}
What do you gonna do ? Eat, Sleep or Read?
hungry <- TRUE # Yes , TRUE , 1
sleepy <- TRUE # Yes , TRUE , 1
if ( ) { # hungry is TRUE and sleepy is TRUE
print(" ")
} else if ( ) { # hungry is TRUE and sleepy is FALSE
print(" ")
} else if ( ) { # hungry is FALSE and sleepy is TRUE
print(" ")
} else { # hungry is FALSE and sleepy is FALSE
print(" ")
}
What do you gonna do ? Eat, Sleep or Read?
hungry <- TRUE # Yes , TRUE , 1
sleepy <- TRUE # Yes , TRUE , 1
if (hungry==TRUE & sleepy==TRUE) { # hungry is TRUE and sleepy is TRUE
print(" ")
} else if (hungry==TRUE & sleepy==FALSE) { # hungry is TRUE and sleepy is FALSE
print(" ")
} else if (hungry==FALSE & sleepy==TRUE) { # hungry is FALSE and sleepy is TRUE
print(" ")
} else { # hungry is FALSE and sleepy is FALSE
print(" ")
}
## [1] " "
What do you gonna do ? Eat, Sleep or Read?
hungry <- TRUE # Yes , TRUE , 1
sleepy <- TRUE # Yes , TRUE , 1
if (hungry==TRUE & sleepy==TRUE) { # hungry is TRUE and sleepy is TRUE
print("EAT")
} else if (hungry==TRUE & sleepy==FALSE) { # hungry is TRUE and sleepy is FALSE
print("EAT")
} else if (hungry==FALSE & sleepy==TRUE) { # hungry is FALSE and sleepy is TRUE
print("SLEEP")
} else { # hungry is FALSE and sleepy is FALSE
print("READ")
}
## [1] "EAT"
An if statement can be placed in another if statement. In the editor, modify the mynumber example once more as follows:
if (...) {
print(...)
}
if (...) {
print("Go to sleep!")
} else {
print("Wake up!")
}
if (...) {
print("I print this when it is true!")
} else {
print(...)
}
ROLE PLAY : You are a CAR, and you are going on the road.
Problem : BUT ;
How can you move ?
Parameters :
You are a CAR, BUT ;
Parameters :
First, define the situation
Traffic_Stop_Light <- 'orange'
Number_of_Pedestrians <- 2
You are a CAR, BUT ;
Traffic_Stop_Light <- 'orange'
Number_of_Pedestrians <- 2
Second, define the conditions to move again
Traffic_Stop_Light : ?
Number_of_Pedestrians : ?
Situation
Traffic_Stop_Light <- 'orange'
Number_of_Pedestrians <- 2
Condition
Traffic_Stop_Light : 'green'
Number_of_Pedestrians : 0
Remember rules
if (...) {
print(...);
} else {
print(...);
}
Situation
Traffic_Stop_Light <- 'orange'
Number_of_Pedestrians <- 2
Condition
Traffic_Stop_Light : 'green'
Number_of_Pedestrians : 0
Remember rules
if ( & ) {
print('Go!');
} else {
print('STOP');
}
Situation
Traffic_Stop_Light <- 'orange'
Number_of_Pedestrians <- 2
Condition
Traffic_Stop_Light : 'green'
Number_of_Pedestrians : 0
Remember rules
if (Traffic_Stop_Light=='green' & Number_of_Pedestrians==0) {
print('Go!');
} else {
print('STOP');
}
## [1] "STOP"
Problem : You want to enjoy, and let’s say the day is;
day <- "Friday"
What do you gonna do if it is Friday.
if (...) {
print('Enjoy the weekend!')
} else {
print('Do some work.')
}
day <- "Friday"
What do you gonna do if it is Friday.
if ( day... | day... ) {
print('Enjoy the weekend!')
} else {
print('Do some work.')
}
ANSWER : You want to enjoy, and let’s say the day is;
day <- "Friday"
It is okay, you can fun if it is weekend.
if (day == 'Saturday' | day == 'Sunday') {
print('Enjoy the weekend!')
} else {
print('Do some work.')
}
## [1] "Do some work."
Problem : You want to go out and your question is
“Should I take an umbrella?”
Note : There are two variables in your code,
“sky” (character) and “high_chance_of_rain” (logical)
Check, if “sky” is equal to “cloudy” and, whether there is a “high_chance_of_rain”.
If both are true, the code should print: “Take umbrella!”
Otherwise, the code should print: “No need for umbrella!”
Based on the condition, what is the answer?
RADIO: The sky is cloudy and the chance of rain is high.
Your conditions, for two variables
# you want to go out and your question is "Should I take an umbrella?"
sky <-
high_chance_of_rain <-
# you want to go out and your question is "Should I take an umbrella?"
sky <- "cloudy"
high_chance_of_rain <- TRUE
# you want to go out and your question is "Should I take an umbrella?"
sky <- "cloudy"
high_chance_of_rain <- TRUE
if (...) {
print("...")
} else {
print("...")
}
if (...) {
print("Take umbrella!")
} else {
print("No need for umbrella!")
}
# you want to go out and your question is "Should I take an umbrella?"
sky <- "cloudy"
high_chance_of_rain <- TRUE
if ( sky... & high_chance_of_rain... ) {
print("Take umbrella!")
} else {
print("No need for umbrella!")
}
# you want to go out and your question is "Should I take an umbrella?"
sky <- "cloudy"
high_chance_of_rain <- TRUE
if (sky == "cloudy" & high_chance_of_rain == TRUE) {
print("Take umbrella!")
} else {
print("No need for umbrella!")
}
## [1] "Take umbrella!"
Objectives
Manage Working Directory
Find the Data
Read Data with utils (R utility functions)
Manage Working Directory
getwd()
## [1] "/Users/emirtoker/Desktop/Memurluk/Software_Tools_for_Earth_&_Environmental_Science/Software_Tools_R_Github"
list.files()
## [1] "_site.yml"
## [2] "about.Rmd"
## [3] "additional_course.Rmd"
## [4] "book.Rmd"
## [5] "code.Rmd"
## [6] "data_download.Rmd"
## [7] "data_sources.Rmd"
## [8] "data_structure.Rmd"
## [9] "data.Rmd"
## [10] "datacamp.Rmd"
## [11] "dc_logo1.png"
## [12] "dc_logo2.png"
## [13] "dc_logo3.png"
## [14] "dc_logo4.png"
## [15] "dc_logo5.png"
## [16] "dc_logo6.png"
## [17] "docs"
## [18] "index.Rmd"
## [19] "LICENSE"
## [20] "my_r_notebook.Rmd"
## [21] "ncl.Rmd"
## [22] "netcdf.Rmd"
## [23] "new_accounts.Rmd"
## [24] "new_data.csv"
## [25] "Presentation"
## [26] "python.Rmd"
## [27] "r_and_rstudio.Rmd"
## [28] "R_Home_Website"
## [29] "R_Interactive_Samples_with_Shiny_files"
## [30] "R_Interactive_Samples_with_Shiny.html"
## [31] "R_Interactive_Samples_with_Shiny.Rmd"
## [32] "R_Interactive_Training"
## [33] "r_language.Rmd"
## [34] "r_probability.Rmd"
## [35] "r_programming.Rmd"
## [36] "r_statistics.Rmd"
## [37] "README.html"
## [38] "README.md"
## [39] "rsconnect"
## [40] "Software_Tools_for_Earth_and_Environmental_Science_Syllabus_2020_21_Fall.png"
## [41] "Software_Tools_for_Earth_and_Environmental_Science_Syllabus.png"
## [42] "Software_Tools_R_Github.Rproj"
## [43] "syllabus.Rmd"
## [44] "unix_linux.Rmd"
Manage Working Directory
# 1
setwd("/Users/emirtoker/Downloads/")
# 2
getwd()
## [1] "/Users/emirtoker/Downloads"
list.files()
## [1] "[15200442 - Journal of Climate] New Insights into the Ocean Heat Budget Closure Problem from Analysis of the SOC Air–Sea Flux Climatology.pdf"
## [2] "[World soils book series] Akça, Erhan_ Günal, Hikmet_ Kapur, S - The soils of Turkey (2018, Springer) - libgen.lc.pdf"
## [3] "1-s2.0-S0967064516302144-main.pdf"
## [4] "129673100.pdf"
## [5] "2014_Book_UsingRForStatistics.pdf"
## [6] "2020-12-23 18-01-23.mkv"
## [7] "255 kodlu taşınırlar.xls"
## [8] "255 kodlu taşınırlar(1).xls"
## [9] "5cf30bfa-7545-4956-91d2-ffcc7761cd42.png"
## [10] "601201020-89206-2020-12-18-09-37-16.html"
## [11] "601201020-89206-2020-12-18-09-37-16.rmd"
## [12] "601202005-89210-2020-12-18-23-45-06.rar"
## [13] "AYBE İklim ve Deniz Ana Bilim Dalı Tanıtım Videosu Akışı .docx"
## [14] "AYBE_İklim_Deniz_ABD_Emir .docx"
## [15] "cru_1901_2012_tmp_TR.nc"
## [16] "ek(1).pdf"
## [17] "FileZilla_3.52.0.5_macosx-x86.app.tar.bz2"
## [18] "JEOA137.pdf"
## [19] "Mediterranean_Basin_Hotspot_2005_Print.tif"
## [20] "MT_Project"
## [21] "S0169809520313107.txt"
## [22] "Software_Tools_Homework_III_Emir.html"
## [23] "turkiye"
## [24] "turkiye.zip"
file.path("~","Users","emirtoker","Downloads","-this_is_my_file.csv")
## [1] "~/Users/emirtoker/Downloads/-this_is_my_file.csv"
Find the Data
# Option 1
# setwd("/Users/emirtoker/Downloads/")
# read.csv("-this_is_my_file.csv")
# Option 2
path <- file.path("~","Users","emirtoker","Downloads","-this_is_my_file.csv")
path
## [1] "~/Users/emirtoker/Downloads/-this_is_my_file.csv"
# read.csv(path)
Read Data
with utils (R utility functions)
Read Data with utils (R utility functions)
read.csv() - Comma Seperated Value
Read Data with utils (R utility functions)
read.delim() - Tab Delimited Data
Read Data with utils (R utility functions)
read.table() - Exocit file format
BONUS - Import Dataset
BONUS - Import Dataset
BONUS - Import Dataset
BONUS - Import Dataset
BONUS - Import Dataset
17061_Sariyer_Sariyer_15dk
<- read.csv( “~/Desktop/NCL_Script_ve_Gorsel/Makale/ time_series_makale/mgm_veri/17061_Sariyer_Sariyer_15dk.txt”, header=FALSE, sep=“;”)
View(17061_Sariyer_Sariyer_15dk
)
~
Manage Directory, Find and Read Data
Instructions
We Have 4 Ways to Read
Manage Directory, Find and Read Data
Instructions - WAY 1 - GO TO FILE
Caraful about header, seperater and missing data
look at the main web page for examples
Manage Directory, Find and Read Data
Instructions - WAY 2 - CALL THE FILE
path_my_file <- file.path("~","Downloads")
precip_2 <- read.table(path_my_file)
Manage Directory, Find and Read Data
Instructions - WAY 3 - IMPORT THE FILE
Manage Directory, Find and Read Data
Instructions - WAY 4 - DOWNLOAD THE FILE
precip_4 <- read.table("link")
Objectives
Identify the Data
Indexing
Use Condition Statements
Plot
Meet with the Data
? dimensions, variables and types ?
month.name
month.abb
attributes(precip_2)
attributes(precip_2)[1]
attributes(precip_2)[[1]]
attributes(precip_2)[[1]] <- c("Year",month.abb)
attr(precip_2,"names") <- c("Year",month.abb)
attr(precip_2,"row.names") <- 1846:2013
precip_2a <- precip_2[-1]
head(precip_2a)
Clear NA and Choose Colomn
precip_2b <- na.omit(precip_2a)
precip_2b_summer <- precip_2b[ ,6:8]
Use Condition Statements - if
mean_jun <- mean(precip_2b_summer$Jun)
mean_jul <- mean(precip_2b_summer$Jul)
if (mean_jun > mean_jul) {
print("June has low precipitation.")
}
colMeans(precip_2b_summer)
Use Condition Statements - else
mean_jun <- mean(precip_2b_summer$Jun)
mean_jul <- mean(precip_2b_summer$Jul)
if (mean_jun < mean_jul) {
print("June has low precipitation.")
} else {
print("June has high precipitation.")
}
colMeans(precip_2b_summer)
Plot
Problem : Extremes and Outliers
plot(precip_2b_summer$Jun,
xlab = "Years",
ylab = "Precipitation [mm/month]",
main = "Istanbul Monthly Precipitation - June",
type = "l",
col="blue")
Plot
Problem : Extremes and Outliers
attr(precip_2b_summer,"row.names")
x_years <- attr(precip_2b_summer,"row.names")
plot(x_years,
precip_2b_summer$Jun,
xlab = "Years",
ylab = "Precipitation [mm/month]",
main = "Istanbul Monthly Precipitation - June",
type = "l",
col="blue")
plot(precip_2b_summer$Aug)
Plot
Problem : Extremes and Outliers
Homework-2
Loops are R’s method for repeating a task, which makes them a useful tool for programming simulations.
repeat
{
message("Happy Groundhog Day!")
break
}
coins <- 3
game <- 0
repeat
{
game <- game + 1
coins <- coins -1
print(game)
print("nice try, play again")
if (coins==0) {
break
}
}
## [1] 1
## [1] "nice try, play again"
## [1] 2
## [1] "nice try, play again"
## [1] 3
## [1] "nice try, play again"
[1] 1
[1] "nice try, play again"
[1] 2
[1] "nice try, play again"
[1] 3
[1] "nice try, play again"
While loops are like backward repeat loops.
while(condition) {
conditional statement
}
coins <- 3
game <- 0
while(coins >= 0)
{
coins <- coins -1
game <- game + 1
print(game)
print("nice try, play again")
}
## [1] 1
## [1] "nice try, play again"
## [1] 2
## [1] "nice try, play again"
## [1] 3
## [1] "nice try, play again"
## [1] 4
## [1] "nice try, play again"
The third type of loop is to be used when you know exactly how many times you want the code to repeat.
for(i in 1:2) {
message("just say it ", i, " times")
}
## just say it 1 times
## just say it 2 times
for(i in c(1,2) ) {
message("just say it ", i, " times")
}
## just say it 1 times
## just say it 2 times
for(i in c("apple","banana") ) {
message("just say it ", i, " times")
}
## just say it apple times
## just say it banana times
it is related with length of vector
month.name
## [1] "January" "February" "March" "April" "May" "June"
## [7] "July" "August" "September" "October" "November" "December"
for(month in month.name) {
message("The month of ", month)
}
## The month of January
## The month of February
## The month of March
## The month of April
## The month of May
## The month of June
## The month of July
## The month of August
## The month of September
## The month of October
## The month of November
## The month of December
apply(X, MARGIN, FUN, ...)
# X is an array or a matrix, dim(X) must have a positive length
# MARGIN=1, it applies over rows, whereas with
# MARGIN=2, it works over columns. Note that when you use the construct
# MARGIN=c(1,2), it applies to both rows and columns
# FUN, which is the function that you want to apply to the data.
apply(precip_2b_summer, MARGIN=1, mean)
apply(precip_2b_summer, MARGIN=2, mean)
apply(precip_2b_summer, MARGIN=c(1,2), mean)
apply(precip_2b_summer, MARGIN=c(2,1), mean)
lapply(precip_2b_summer,"[",1)
sapply(precip_2b_summer,"[",1)
Practice : Write A Function - 3
my_fun3 <- function(w,x,y,z){
result1 <- w+x
result2 <- y*z
print(result1)
print(result2)
}
# my_fun3()
my_fun3(1,2,3,4)
## [1] 3
## [1] 12
BONUS
menu(c("Yes", "No"), title="What dou you think?")
menu1 <- menu(c("Yes", "No"), title="What dou you think?")
menu1
menu(c("Option1","Option2","Option3","Option4"), title="Choose one of them")
menu2 <- menu(c("Option1","Option2","Option3","Option4"), title="Choose one of them")
menu2
my_fun3 <- function(x,y){
math <- menu(c("+", "-", "*", "/"), title="Which calculation?")
if (math==1) {
result <- x+y
} else if ( ) {
} else if ( ) {
} else {
}
print(result)
}
Practice : Write An IF-Statement - 2
worry_flow <- function() {
answer1 <- menu(c("Yes","No"), title = "Do you have a problem in your life ?")
if (answer1 == 2) {
print("Then Don't Worry")
}
else {
answer2 <- menu(c("Yes","No"), title = "Can you do something about it ?")
if(answer2 == 1){
print("Then Don't Worry")
}
else{
print("Then Don't Worry")
}
}
require(tcltk)
msgBox <- tkmessageBox(title = "Title of message box",
message = "THEN WYH WORRY!",
icon = "info",
type = "ok")
}