R Programming - Conditions

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

if (Stand-Alone) Statement

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!")
a <- 3
num <- 4

if ( a <= num ) {
a <- a ^ 2
}

a
## [1] 9

if (Stand-Alone) Statement

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

if (Stand-Alone) Statement


if (Stand-Alone) Statement


else - Statement

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
dec <- 0.5

if (dec <= 0.5) {
  adec <- dec + 1
} else {
  adec <- dec
}

adec
## [1] 1.5

-else - and -else if- Statement

If your situation has more than two mutually exclusive cases, use else and if statements together.

a <- 1 
b <- 1 

if (a > b) { 
  print("A wins!")
} else if (a < b) { 
  print("B wins!")
} else {
  print("Tie.")
}
## [1] "Tie."

Nesting and Stacking Statements

An if statement can be placed in another if statement. In the editor, modify the mynumber example once more as follows:


Nesting and Stacking Statements


Nesting and Stacking Statements


Nesting and Stacking Statements


Nesting and Stacking Statements


Practice - Conditions - TRUE and FALSE

  1. Print this if it is TRUE. “This message will print!”
if (...) {
  print(...)
} 
  1. Go to sleep if it is TRUE, else wake up.
if (...) {
   print("Go to sleep!")
} else {
   print("Wake up!")
}
  1. The variable message to “I execute this when true!” when the condition is TRUE.
if (...) {
  message <- "..."
  print(message)
} else {
  message <- "I execute this when false!"
  print(...)
}

Practice - Conditions - Logical Op

Problem : You are a CAR, and you are going on the road, BUT ;

Car_Stop_Light <- 'orange'
Number_of_Pedestrians <- 2

Remember rules

if (...) {
  print(...);
} else {
  print(...);
}

Practice - Conditions - Logical Op

ANSWER : You are a CAR, and you are going on the road, BUT ;

Car_Stop_Light <- 'orange'
Number_of_Pedestrians <- 2

Remember rules

if (Car_Stop_Light == 'green' & Number_of_Pedestrians ==0) {
  print('Go!');
} else {
  print('STOP');
}
## [1] "STOP"

Practice - Conditions - Logical Op

Problem : You want to enjoy, and let’s say the day is;

day <- "Saturday"

It is okay, you can fun if it is weekend.

if (...) {
  print('Enjoy the weekend!')
} else {
  print('Do some work.')
}

Practice - Conditions - Logical Op

ANSWER : You want to enjoy, and let’s say the day is;

day <- "Saturday"

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] "Enjoy the weekend!"

Practice - Conditions - Logical Op

Problem : You want to go out and your question is “Should I take an umbrella?”

  • Check to see, if “weather” is “equal” to “cloudy” and, whether there is a “high_chance_of_rain”.
  • If it is both, the code should assign the value of the variable message to be “Take umbrella!”
  • Otherwise, the code should assign the value of the variable message to “No need for umbrella!”
  • Print the message variable after the conditional statement.
  • Based on the condition, what should its value be?

Note : There are two variables in your code, “weather” and “high_chance_of_rain”


Practice - Conditions - Logical Op

# you want to go out and your question is "Should I take an umbrella?"

message <- 'Should I take an umbrella?'

weather <- "cloudy"

high_chance_of_rain <- TRUE

Practice - Conditions - Logical Op

# you want to go out and your question is "Should I take an umbrella?"

message <- 'Should I take an umbrella?'

weather <- "cloudy"

high_chance_of_rain <- TRUE
if (...) {
  message <- 'Take umbrella!'
  print(message)
} else { 
  message <- 'No need for umbrella!'
  print(message)
  }

Practice - Conditions - Logical Op

# you want to go out and your question is "Should I take an umbrella?"

message <- 'Should I take an umbrella?'

weather <- "cloudy"

high_chance_of_rain <- TRUE

if (weather == "cloudy" & high_chance_of_rain == TRUE) {
  message <- 'Take umbrella!'
  print(message)
} else { 
  message <- 'No need for umbrella!'
  print(message)
  }
## [1] "Take umbrella!"

Practice - R Language

Objectives

  • Manage Working Directory

  • Find the Data

  • Read Data with utils (R utility functions)


Practice - R Language

Manage Working Directory

  • getwd() - get working directory
  • list.files() # or dir()
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_sources.Rmd"                                                            
##  [7] "data_structure.Rmd"                                                          
##  [8] "data.Rmd"                                                                    
##  [9] "datacamp.Rmd"                                                                
## [10] "dc_logo1.png"                                                                
## [11] "dc_logo2.png"                                                                
## [12] "dc_logo3.png"                                                                
## [13] "dc_logo4.png"                                                                
## [14] "dc_logo5.png"                                                                
## [15] "docs"                                                                        
## [16] "index.Rmd"                                                                   
## [17] "LICENSE"                                                                     
## [18] "my_r_notebook.Rmd"                                                           
## [19] "ncl.Rmd"                                                                     
## [20] "netcdf.Rmd"                                                                  
## [21] "new_accounts.Rmd"                                                            
## [22] "new_data.csv"                                                                
## [23] "Presentation"                                                                
## [24] "python.Rmd"                                                                  
## [25] "r_and_rstudio.Rmd"                                                           
## [26] "R_Home_Website"                                                              
## [27] "R_Interactive_Samples_with_Shiny_files"                                      
## [28] "R_Interactive_Samples_with_Shiny.html"                                       
## [29] "R_Interactive_Samples_with_Shiny.Rmd"                                        
## [30] "R_Interactive_Training"                                                      
## [31] "r_language.Rmd"                                                              
## [32] "r_probability.Rmd"                                                           
## [33] "r_programming.Rmd"                                                           
## [34] "r_statistics.Rmd"                                                            
## [35] "README.html"                                                                 
## [36] "README.md"                                                                   
## [37] "rsconnect"                                                                   
## [38] "Software_Tools_for_Earth_and_Environmental_Science_Syllabus_2020_21_Fall.png"
## [39] "Software_Tools_for_Earth_and_Environmental_Science_Syllabus.png"             
## [40] "Software_Tools_R_Github.Rproj"                                               
## [41] "syllabus.Rmd"                                                                
## [42] "unix_linux.Rmd"

Practice - R Language

Manage Working Directory

  • setwd() - set working directory
# 1
setwd("/Users/emirtoker/Downloads/")
# 2
getwd()
## [1] "/Users/emirtoker/Downloads"
list.files()
##   [1] "_grib2netcdf-webmars-public-svc-green-007-6fe5cac1a363ec1525f54343b6cc9fd8-8LiuI0.nc"                                                                                                                  
##   [2] "-1396197156987262396..xls"                                                                                                                                                                             
##   [3] "-5211097752695221187..xls"                                                                                                                                                                             
##   [4] "-7376906819256400609..xls"                                                                                                                                                                             
##   [5] "-953619339638234986..xls"                                                                                                                                                                              
##   [6] "-969412494327541903..xls"                                                                                                                                                                              
##   [7] "(Cambridge Atmospheric and Space Science Series) Boris A. Kagan - Ocean Atmosphere Interaction and Climate Modeling-Cambridge University Press (2006).pdf"                                             
##   [8] "(International Geophysics 101) Benoit Cushman-Roisin and Jean-Marie Beckers (Eds.) - Introduction to Geophysical Fluid Dynamics_ Physical and Numerical Aspects-Academic Press (2011).pdf"             
##   [9] "(International Geophysics 103) Gerold Siedler, Stephen M. Griffies, John Gould and John A. Church (Eds.) - Ocean Circulation and Climate_ A 21 Century Perspective-Academic Press, Elsevier (2013).pdf"
##  [10] "(Introduction to Geophysical 101) Benoit Cushman-Roisin, Jean-Marie Beckers - Introduction to Geophysical Fluid Dynamics_ Physical and Numerical Aspects-Academic Press (2011).pdf"                    
##  [11] "1-s2.0-S0169809511000366-main.pdf"                                                                                                                                                                     
##  [12] "1-s2.0-S0169809512001561-main.pdf"                                                                                                                                                                     
##  [13] "1-s2.0-S016980951200347X-main (1).pdf"                                                                                                                                                                 
##  [14] "1-s2.0-S016980951200347X-main (2).pdf"                                                                                                                                                                 
##  [15] "1-s2.0-S016980951200347X-main.pdf"                                                                                                                                                                     
##  [16] "1-s2.0-S0169809513003669-main.pdf"                                                                                                                                                                     
##  [17] "1-s2.0-S0169809514003913-main.pdf"                                                                                                                                                                     
##  [18] "1-s2.0-S0169809516304537-main.pdf"                                                                                                                                                                     
##  [19] "1-s2.0-S0169809516307189-main.pdf"                                                                                                                                                                     
##  [20] "1-s2.0-S016980951931347X-main.pdf"                                                                                                                                                                     
##  [21] "1-s2.0-S0169809520301071-main.pdf"                                                                                                                                                                     
##  [22] "1-s2.0-S0277379114000298-mmc1 (1).kmz"                                                                                                                                                                 
##  [23] "1-s2.0-S0277379114000298-mmc1.kmz"                                                                                                                                                                     
##  [24] "10113034.pdf"                                                                                                                                                                                          
##  [25] "14. Granulit, Eklojit.pptx"                                                                                                                                                                            
##  [26] "16638_F.pdf"                                                                                                                                                                                           
##  [27] "19394386126_Akademisyen.pdf"                                                                                                                                                                           
##  [28] "19394386126_Ogrenci.pdf"                                                                                                                                                                               
##  [29] "1963_Book_SevereLocalStorms.pdf"                                                                                                                                                                       
##  [30] "2_AVICENA_-_Authors_statement_for_publication.doc"                                                                                                                                                     
##  [31] "2015_OCEAN820_Final_engl.pdf"                                                                                                                                                                          
##  [32] "2018_Korotenko_peerj-5448.pdf"                                                                                                                                                                         
##  [33] "2019_eş-danışman-atama-dilekçesi.docx"                                                                                                                                                                 
##  [34] "2019JD031403.pdf"                                                                                                                                                                                      
##  [35] "2020JournalImpactFactorandQuartile.pdf"                                                                                                                                                                
##  [36] "3400534.acsm"                                                                                                                                                                                          
##  [37] "3759624810925922053..xls"                                                                                                                                                                              
##  [38] "465-Article Text-1246-1-10-20111104.pdf"                                                                                                                                                               
##  [39] "601151011.pdf"                                                                                                                                                                                         
##  [40] "6583231.png"                                                                                                                                                                                           
##  [41] "8174-era-interim-archive-version-20.pdf"                                                                                                                                                               
##  [42] "86773.pdf"                                                                                                                                                                                             
##  [43] "A_Novel_and_Scalable_Spatio-Temporal_Technique_for.pdf"                                                                                                                                                
##  [44] "a3_hafta_cizelge_zoom_link_V2.xlsx - Sheet2.pdf"                                                                                                                                                       
##  [45] "a3_hafta_cizelge_zoom_link.xlsx - Sheet2.pdf"                                                                                                                                                          
##  [46] "a4_TURQUA_2020_Programı_V3 (1).xlsx"                                                                                                                                                                   
##  [47] "a4_TURQUA_2020_Programı_V3.xlsx"                                                                                                                                                                       
##  [48] "a4_TURQUA_2020_Programı_V3.xlsx - Program  (1).pdf"                                                                                                                                                    
##  [49] "a4_TURQUA_2020_Programı_V3.xlsx - Program .pdf"                                                                                                                                                        
##  [50] "a4_TURQUA_2020_Programı_V4.xlsx"                                                                                                                                                                       
##  [51] "a4_TURQUA_2020_Programı_V8.xlsx - Program .pdf"                                                                                                                                                        
##  [52] "AGU2017_poster_XZ.pdf"                                                                                                                                                                                 
##  [53] "Akarsu_Jeomorfolojisi_Lec6.pdf"                                                                                                                                                                        
##  [54] "Akiskanlar_Mekanigi_rev.pdf"                                                                                                                                                                           
##  [55] "angeo-21-21-2003.pdf"                                                                                                                                                                                  
##  [56] "APR-D2000240-ResponsetoReviewers-Rev02.docx"                                                                                                                                                           
##  [57] "Argor_oturumlar.pdf"                                                                                                                                                                                   
##  [58] "atmosphere-09-00106.pdf"                                                                                                                                                                               
##  [59] "atmosphere-09-00378.pdf"                                                                                                                                                                               
##  [60] "ATMOSRES-D-20-00012 (1).pdf"                                                                                                                                                                           
##  [61] "ATMOSRES-D-20-00012_R1.pdf"                                                                                                                                                                            
##  [62] "ATMOSRES-D-20-00012_reviewer_comments.pdf"                                                                                                                                                             
##  [63] "ATMOSRES-D-20-00012.pdf"                                                                                                                                                                               
##  [64] "AX88179_178A_Macintosh_Driver_Installer_v2.9.0_20171011.zip"                                                                                                                                           
##  [65] "AX88179_178A_macOS_10.15_above_Driver_Installer_v2.16.0 (1).zip"                                                                                                                                       
##  [66] "AX88179_178A_macOS_10.15_above_Driver_Installer_v2.16.0 2"                                                                                                                                             
##  [67] "AX88179_178A_macOS_10.15_above_Driver_Installer_v2.16.0.zip"                                                                                                                                           
##  [68] "aybe_seminerbilgiformu.docx"                                                                                                                                                                           
##  [69] "Bae2019_Article_DevelopmentOfASingle-MomentClo (1).pdf"                                                                                                                                                
##  [70] "Bae2019_Article_DevelopmentOfASingle-MomentClo.pdf"                                                                                                                                                    
##  [71] "BAP_Uygulama_Esasları_Kılavuz_28_04_2020_v3 (1).pdf"                                                                                                                                                   
##  [72] "BAP_Uygulama_Esasları_Kılavuz_28_04_2020_v3.pdf"                                                                                                                                                       
##  [73] "Basvuru_Formu.doc"                                                                                                                                                                                     
##  [74] "Besiktepe_1994_circulation_hydrography.pdf"                                                                                                                                                            
##  [75] "C. Donald Ahrens, Robert Henson - Essentials of Meteorology_ An Invitation to the Atmosphere-Cengage Learning (2018).pdf"                                                                              
##  [76] "CBO9781107707405.011.pdf"                                                                                                                                                                              
##  [77] "check_input_data"                                                                                                                                                                                      
##  [78] "Chevuturi-Dimri2015_Article_Inter-comparisonOfPhysicalProc.pdf"                                                                                                                                        
##  [79] "cintineo_mwr_jan2014.pdf"                                                                                                                                                                              
##  [80] "citation-318968783.ris"                                                                                                                                                                                
##  [81] "climate-05-00048-v2.pdf"                                                                                                                                                                               
##  [82] "Committee on the Earth system Context for Hominin Evolution, National Research Council - Understanding Climate's Influence on Human Evolution (2010).pdf"                                              
##  [83] "deniz-biyolojisi-6.pdf"                                                                                                                                                                                
##  [84] "deniz-planktonlari-ve-ekolojisi1.pdf"                                                                                                                                                                  
##  [85] "Density_colorbar_1000x500 (1).tif"                                                                                                                                                                     
##  [86] "Density_colorbar_1000x500.tif"                                                                                                                                                                         
##  [87] "Diffenbaugh-2020-The-covid--lockdowns-a-window-into-.pdf"                                                                                                                                              
##  [88] "dinamiknot1.doc"                                                                                                                                                                                       
##  [89] "DiversityofbacteriaisolatedfromTurkishmarineareas.pdf"                                                                                                                                                 
##  [90] "doğrudan-temin-onay-belgesi.xls"                                                                                                                                                                       
##  [91] "doktora-yeterlik-sınavı-başvuru-formu-g_1935ee314bceeb6433bf21ff0000f8c30df1333a4bceeb6433bf21ff0000f8c30d.doc"                                                                                        
##  [92] "Dropbox"                                                                                                                                                                                               
##  [93] "Dropbox.zip"                                                                                                                                                                                           
##  [94] "DSM_DS1515+_25426.pat"                                                                                                                                                                                 
##  [95] "efi_what_science_can_tell_us_1_2011_en.pdf"                                                                                                                                                            
##  [96] "Emir_Comments_Response_V5_YE.docx"                                                                                                                                                                     
##  [97] "Emir_Paper_Revision_V1_YE.docx"                                                                                                                                                                        
##  [98] "Emir_Paper_Revision_V3_YE.docx"                                                                                                                                                                        
##  [99] "Evaluation_of_the_WRF_model_with_different_domain_.pdf"                                                                                                                                                
## [100] "Evidence that the Great Pacifc Garbage Patch is rapidly accumulating plastic.pdf"                                                                                                                      
## [101] "Ezber-2015-Investigation-of-local-flow-feature (1).pdf"                                                                                                                                                
## [102] "Ezber-2015-Investigation-of-local-flow-feature.pdf"                                                                                                                                                    
## [103] "FileZilla_3.49.1_macosx-x86.app.tar.bz2"                                                                                                                                                               
## [104] "FileZilla_3.50.0_macosx-x86.app.tar.bz2"                                                                                                                                                               
## [105] "Frederick K. Lutgens_ Edward J. Tarbuck - The atmosphere_ an introduction to meteorology (2016, Pearson) - libgen.lc.pdf"                                                                              
## [106] "Frederick K. Lutgens_ Edward J. Tarbuck - The atmosphere_ an introduction to meteorology-Pearson (2016).pdf"                                                                                           
## [107] "Friedlingstein-2019-Global-carbon-budget-.pdf"                                                                                                                                                         
## [108] "Gao2011_Article_ATwo-momentBulkMicrophysicsCou.pdf"                                                                                                                                                    
## [109] "Gimeno-etal-2012-RevGeophys.pdf"                                                                                                                                                                       
## [110] "gmd-2019-349 (1).bib"                                                                                                                                                                                  
## [111] "gmd-2019-349 (1).ris"                                                                                                                                                                                  
## [112] "gmd-2019-349 (2).bib"                                                                                                                                                                                  
## [113] "gmd-2019-349 (3).bib"                                                                                                                                                                                  
## [114] "gmd-2019-349.bib"                                                                                                                                                                                      
## [115] "gmd-2019-349.ris"                                                                                                                                                                                      
## [116] "IJG_2013090916272381.pdf"                                                                                                                                                                              
## [117] "ijgi-08-00204-v2.pdf"                                                                                                                                                                                  
## [118] "Impact_of_Highly_Reflective_Materials_on_Meteorolo.pdf"                                                                                                                                                
## [119] "inputdata_checksum.dat"                                                                                                                                                                                
## [120] "Install League of Legends euw.app"                                                                                                                                                                     
## [121] "Install League of Legends euw.zip"                                                                                                                                                                     
## [122] "Introductory Dynamical Oceanography by Stephen Pond and G L Pickard (Auth.) (z-lib.org).pdf"                                                                                                           
## [123] "ipynb.ipynb"                                                                                                                                                                                           
## [124] "ITU_bap_yonerge_16_04_2019_v3 (1).pdf"                                                                                                                                                                 
## [125] "ITU_bap_yonerge_16_04_2019_v3.pdf"                                                                                                                                                                     
## [126] "IVD-Alindi-bU85GQ9XV8.pdf"                                                                                                                                                                             
## [127] "Jane H. Hodgkinson, Frank D. Stacey - Practical Handbook of Earth Science-Taylor & Francis_CRC Press (2017).pdf"                                                                                       
## [128] "Jim Bell - The Earth Book_ From the Beginning to the End of Our Planet, 250 Milestones in the History of Earth Science-Sterling Publishing Co. Inc. (2019).pdf"                                        
## [129] "joc.4457.pdf"                                                                                                                                                                                          
## [130] "Kevin Hamilton (auth.), Kevin Hamilton, Wataru Ohfuchi (eds.) - High Resolution Numerical Modelling of the Atmosphere and Ocean-Springer-Verlag New York (2008) (1).pdf"                               
## [131] "KiraPfoch_2019_Poster_ESA_Louvain-la-Neuve.pdf"                                                                                                                                                        
## [132] "klt-trh-un-1.pdf"                                                                                                                                                                                      
## [133] "klt-trh-un-2.pdf"                                                                                                                                                                                      
## [134] "Launiainen_etal_2013Ambio.pdf"                                                                                                                                                                         
## [135] "makale çalışma 180820.docx"                                                                                                                                                                            
## [136] "manual.pdf"                                                                                                                                                                                            
## [137] "mdinhawaii.pdf"                                                                                                                                                                                        
## [138] "Midlatitude Synoptic Meteorology Dynamics, Analysis, and Forecasting by Gary Lackmann (z-lib.org).pdf"                                                                                                 
## [139] "model_description_template_lpjg21.doc"                                                                                                                                                                 
## [140] "Moya-Álvarez2019_Article_ResponseOfTheWRFModelToDiffere.pdf"                                                                                                                                           
## [141] "Müh Jeo-3 Mineral ve kayaçlar.pdf"                                                                                                                                                                     
## [142] "Murthy2018_Article_WRFSimulationOfASevereHailstor.pdf"                                                                                                                                                 
## [143] "MY1DMM_CHLORA-MYD28M.mov"                                                                                                                                                                              
## [144] "MY1DMM_CHLORA.mov"                                                                                                                                                                                     
## [145] "Neil C. Wells - The Atmosphere and Ocean_ A Physical Introduction (Advancing Weather and Climate Science)-Wiley (2012).pdf"                                                                            
## [146] "New Recording 6.m4a"                                                                                                                                                                                   
## [147] "noaa_7088_DS1.pdf"                                                                                                                                                                                     
## [148] "ornek.docx"                                                                                                                                                                                            
## [149] "ÖSYM Aday İşlemleri Sistemi - Sınav Başvuru Kayıt Bilgileri Elif Gözler.pdf"                                                                                                                           
## [150] "ÖSYM Aday İşlemleri Sistemi - Sınav Başvuru Kayıt Bilgileri.pdf"                                                                                                                                       
## [151] "ÖSYM Sonuç Açıklama Sistemi (1).pdf"                                                                                                                                                                   
## [152] "ÖSYM Sonuç Açıklama Sistemi.pdf"                                                                                                                                                                       
## [153] "Ozgecmis_Formu.doc"                                                                                                                                                                                    
## [154] "PanoplyMacOS-4.11.4.dmg"                                                                                                                                                                               
## [155] "Paper_forpreprintserver (1).pdf"                                                                                                                                                                       
## [156] "Paper_forpreprintserver.pdf"                                                                                                                                                                           
## [157] "PDF Datastream.pdf"                                                                                                                                                                                    
## [158] "PDF_TL_11_06_08_A.pdf"                                                                                                                                                                                 
## [159] "pericles_1944920858.enw"                                                                                                                                                                               
## [160] "pericles_1944920858.txt"                                                                                                                                                                               
## [161] "piyasa-fiyat-araştırma-tutanağı1b8bee4aceeb6433bf21ff0000f8c30d.xls"                                                                                                                                   
## [162] "pngbarn (1).png"                                                                                                                                                                                       
## [163] "pngbarn.png"                                                                                                                                                                                           
## [164] "PngItem_201916.png"                                                                                                                                                                                    
## [165] "Potential_Temperature.pdf"                                                                                                                                                                             
## [166] "pr_MNA-44_CNRM-CERFACS-CNRM-CM5_historicalandrcp85_r1i1p1_SMHI-RCA4_v1-bc-dbs-wfdei_day_19510101-21001231_2046_2046.nc"                                                                                
## [167] "pr_MNA-44_CNRM-CERFACS-CNRM-CM5_historicalandrcp85_r1i1p1_SMHI-RCA4_v1-bc-dbs-wfdei_day_19510101-21001231_2046_2046.nc.aux.xml"                                                                        
## [168] "pr_mna-44_cnrm-cerfacs-cnrm-cm5_historicalandrcp85_r1i1p1_smhi-rca4_v1-bc-dbs-wfdei_day_19510101-21001231_2046_2046.zip"                                                                               
## [169] "qgis-macos-ltr.dmg"                                                                                                                                                                                    
## [170] "qj.49708737407.pdf"                                                                                                                                                                                    
## [171] "qj.49709942229.pdf"                                                                                                                                                                                    
## [172] "QNAPQfinderProMac-7.4.0.0731.dmg"                                                                                                                                                                      
## [173] "R1T8MA.jpg"                                                                                                                                                                                            
## [174] "RD9700 Mac Driver"                                                                                                                                                                                     
## [175] "RD9700 Mac Driver 2"                                                                                                                                                                                   
## [176] "RD9700 Mac Driver 3"                                                                                                                                                                                   
## [177] "rd9700-mac-driver (1).zip"                                                                                                                                                                             
## [178] "rd9700-mac-driver (2).zip"                                                                                                                                                                             
## [179] "rd9700-mac-driver.zip"                                                                                                                                                                                 
## [180] "remotesensing-09-01143-v2.pdf"                                                                                                                                                                         
## [181] "remotesensing-12-02253-v2.pdf"                                                                                                                                                                         
## [182] "Review_AtmoRes-D-20-00012.pdf"                                                                                                                                                                         
## [183] "roisinGFD2010.pdf"                                                                                                                                                                                     
## [184] "S0169809520300375.bib"                                                                                                                                                                                 
## [185] "S0169809520300375.ris"                                                                                                                                                                                 
## [186] "S0169809520300375.txt"                                                                                                                                                                                 
## [187] "Sarah Cornell_ I  Colin Prentice_ Joanna House_ Catherine Downy - Understanding the earth system _ global change science for application-Cambridge University Press (2012).pdf"                        
## [188] "sari2018.pdf"                                                                                                                                                                                          
## [189] "ScienceDirect_articles_22Jul2020_22-19-21.653"                                                                                                                                                         
## [190] "ScienceDirect_articles_22Jul2020_22-19-21.653.zip"                                                                                                                                                     
## [191] "Seasonally_asymmetric_transition_of_the_Asian_mons.pdf"                                                                                                                                                
## [192] "singh2015.pdf"                                                                                                                                                                                         
## [193] "snw_cvr"                                                                                                                                                                                               
## [194] "snw_cvr.rar"                                                                                                                                                                                           
## [195] "Song-Sohn2018_Article_AnEvaluationOfWRFMicrophysicsS.pdf"                                                                                                                                              
## [196] "SSRN-id3550308.pdf"                                                                                                                                                                                    
## [197] "SSS_colorbar_1000x500.tif"                                                                                                                                                                             
## [198] "SST_colorbar_1000x500.tif"                                                                                                                                                                             
## [199] "sst.wkmean.1981-1989.nc"                                                                                                                                                                               
## [200] "sst.wkmean.1990-present.nc"                                                                                                                                                                            
## [201] "Stephen Pond and G L Pickard (Auth.) - Introductory Dynamical Oceanography (1983) - libgen.lc.pdf"                                                                                                     
## [202] "Supplementary_Toker_et_al_Revised.pptx"                                                                                                                                                                
## [203] "synology-assistant-6.2-24922.dmg"                                                                                                                                                                      
## [204] "tez-projeleri-bursiyer-bilgi-formu.docx"                                                                                                                                                               
## [205] "The_Making_of_the_New_European_Wind_Atlas_Part_1_M.pdf"                                                                                                                                                
## [206] "Thomas D. Potter, Bradley R. Colman - Handbook of Weather, Climate and Water_ Dynamics, Climate, Physical Meteorology, Weather Systems, and Measurements-Wiley-Interscience (2003).pdf"                
## [207] "TM_NWS_ER_69.pdf"                                                                                                                                                                                      
## [208] "Toker-11.12.19.pdf"                                                                                                                                                                                    
## [209] "turqua20_kurs.csv"                                                                                                                                                                                     
## [210] "turqua20_kurs.csv.zip"                                                                                                                                                                                 
## [211] "turqua20_kuvaterner_atolye.csv"                                                                                                                                                                        
## [212] "turqua20_kuvaterner_atolye.csv.zip"                                                                                                                                                                    
## [213] "turqua20_Quaternary_workshop.csv"                                                                                                                                                                      
## [214] "turqua20_Quaternary_workshop.csv.zip"                                                                                                                                                                  
## [215] "turqua20_R_atolye.csv"                                                                                                                                                                                 
## [216] "Unite_4.pdf"                                                                                                                                                                                           
## [217] "Unite_9 (1).pdf"                                                                                                                                                                                       
## [218] "Unite_9.pdf"                                                                                                                                                                                           
## [219] "unluata_etal.pdf"                                                                                                                                                                                      
## [220] "video 2.MOV"                                                                                                                                                                                           
## [221] "video.MOV"                                                                                                                                                                                             
## [222] "Vorticity.PDF"                                                                                                                                                                                         
## [223] "Wang_etal_hess-2012 (1).pdf"                                                                                                                                                                           
## [224] "Wang_etal_hess-2012.pdf"                                                                                                                                                                               
## [225] "Water Exchange through Canal İstanbul and Bosphorus Strait.pdf"                                                                                                                                        
## [226] "wct-4.5.1"                                                                                                                                                                                             
## [227] "wct-4.5.1.zip"                                                                                                                                                                                         
## [228] "WhatsApp Image 2020-07-14 at 00.31.59.jpeg"                                                                                                                                                            
## [229] "WINDS 850 - 4 SEASONS.docx"                                                                                                                                                                            
## [230] "Zhang2018_Article_ApplyingTheWRFDouble-MomentSix.pdf"                                                                                                                                                  
## [231] "د. عزام أبو حبيب.pptx"
file.path("~","Users","emirtoker","Downloads","-this_is_my_file.csv")
## [1] "~/Users/emirtoker/Downloads/-this_is_my_file.csv"

Practice - R Language

Find the Data

  • file.path()
# 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)

Practice - R Language

Read Data

with utils (R utility functions)

  • read.csv() - Comma Seperated Value
  • read.delim() - Tab Delimited Data
  • read.table() - Exocit file format

Practice - R Language

Read Data with utils (R utility functions)

read.csv() - Comma Seperated Value


Practice - R Language

Read Data with utils (R utility functions)

read.delim() - Tab Delimited Data


Practice - R Language

Read Data with utils (R utility functions)

read.table() - Exocit file format


Practice - R Language

BONUS - Import Dataset


Practice - R Language

BONUS - Import Dataset


Practice - R Language

BONUS - Import Dataset


Practice - R Language

BONUS - Import Dataset


Practice - R Language

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)

~


Practice - R Language

Manage Directory, Find and Read Data

Instructions

  1. Go to main webpage of course
  2. Open Data “Istanbul_Goztepe_Precipitation_1846-2013_Monthly” (.dat) LINK
  3. Copy and Paste it in your “Downloads” directory in a text file
  4. Open your R Studio

We Have 4 Ways to Read


Practice - R Language

Manage Directory, Find and Read Data

Instructions - WAY 1 - GO TO FILE

  1. Check your Project Name and your Working directory
  2. Go to “Downloads” directory in R Studio
  3. List files and Read Data with three different read functions
    • read.csv()
    • read.delim()
    • read.table()
  4. Choose the best
  5. Assign your data as “precip_1”

Caraful about header, seperater and missing data

look at the main web page for examples


Practice - R Language

Manage Directory, Find and Read Data

Instructions - WAY 2 - CALL THE FILE

  1. Go Back to your Working directory
  2. Define your file path with file.path()
  3. Assign the path a new variable as “path_my_file”
  4. Use your best read() function
  5. Read the file with “path_my_file”
  6. Assign your data as “precip_2”
path_my_file <- file.path("~","Downloads")
precip_2 <- read.table(path_my_file)

Practice - R Language

Manage Directory, Find and Read Data

Instructions - WAY 3 - IMPORT THE FILE

  1. Use “Import Datase”
  2. Assign your data as “precip_3”

Practice - R Language

Manage Directory, Find and Read Data

Instructions - WAY 4 - DOWNLOAD THE FILE

  1. Copy the LINK of data
  2. Use your best read() function
  3. Read the file with this function and LINK
  4. Assign your data as “precip_4”
precip_4 <- read.table("link")

Practice - R Programming


Practice - R Programming

Objectives

  • Identify the Data

  • Indexing

  • Use Condition Statements

  • Plot


Practice - R Programming

Meet with the Data

  1. Look at structure
  2. Learn attributes and dimensions
  3. Rename attributes

? 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)

Practice - R Programming

Clear NA and Choose Colomn

  1. Print “precip_2a”
  2. Delete rows which include NA ( na.omit() )
  3. Assign it as “precip_2b”
  4. Select summer season
  5. Assign it as “precip_2b_summer”
precip_2b <- na.omit(precip_2a)
precip_2b_summer <- precip_2b[ ,6:8]

Practice - R Programming

Use Condition Statements - if

  1. Compare June Mean Precipitation with July
  2. IF June mean precipitation is LOWER than July then print “June has low precipitation.”
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)

Practice - R Programming

Use Condition Statements - else

  1. IF June mean precipitation is LOWER than July then print “June has low precipitation.”
  2. ELSE print “June has high precipitation.”
  3. Calculate mean of each month ( colMeans() )
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)

Practice - R Programming

Plot

Problem : Extremes and Outliers

  1. Plot precipitation for June
  2. Add title and unit
plot(precip_2b_summer$Jun, 
    xlab = "Years",
    ylab = "Precipitation [mm/month]", 
    main = "Istanbul Monthly Precipitation - June", 
    type = "l", 
    col="blue")

Practice - R Programming

Plot

Problem : Extremes and Outliers

  1. Edit x-axis, which years are they ?
  2. What about August ?
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)

Practice - R Programming

Plot

Problem : Extremes and Outliers

Homework-2


R Programming - Loops

Loops are R’s method for repeating a task, which makes them a useful tool for programming simulations.


R Programming - repeat Loops

repeat
{
  message("Happy Groundhog Day!")
  break
}

R Programming - repeat Loops

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"

R Programming - while Loops

While loops are like backward repeat loops.

while(condition) {
conditional statement
}

R Programming - while Loops

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"

R Programming - for Loops

The third type of loop is to be used when you know exactly how many times you want the code to repeat.


R Programming - for Loops

for(i in 1:2) {
message("just say it ", i, " times")
}
## just say it 1 times
## just say it 2 times

R Programming - for Loops

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


R Programming - for Loops

month.name
##  [1] "January"   "February"  "March"     "April"     "May"      
##  [6] "June"      "July"      "August"    "September" "October"  
## [11] "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

R Programming - apply Loops

  • The apply() functions form the basis of more complex combinations and helps to perform operations with very few lines of code.
  • More specifically, the family is made up of the apply(), lapply() , sapply(), vapply(), mapply(), rapply(), and tapply() functions.
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)

R Programming - apply Loops


R Programming - lapply Loops

lapply(precip_2b_summer,"[",1)

sapply(precip_2b_summer,"[",1)