#R Notes for the Book "Climate Mathematics With R" 
#by SSP Shen and RCJ Somerville
#Cambridge University Press, 2018
#
#R Programming for Climate Data Analysis and Visualization
#
#
#Samuel S.P. Shen used these R codes to teach
#Short Courses on R Programming for Climate Science 
#at NOAA-NCEI, Asheville, USA in May 2017 and 
#Chinese Academy of Sciences, Beijing, China in June 2017 

###################################################
#Chapter 2 of the Book "Climate Mathematics With R"
###################################################
#
#Define a sequence
#The same sequence 1,2, ..., 8 can be generated by different commands
1:8
## [1] 1 2 3 4 5 6 7 8
seq(1,8)
## [1] 1 2 3 4 5 6 7 8
seq(8)
## [1] 1 2 3 4 5 6 7 8
seq(1,8, by=1)
## [1] 1 2 3 4 5 6 7 8
seq(1,8, length=8)
## [1] 1 2 3 4 5 6 7 8
seq(1,8, length.out =8)
## [1] 1 2 3 4 5 6 7 8
#Define a function
samfctn <- function(x) x*x
#Evaluate the function value 
samfctn(4)
## [1] 16
fctn2 <- function(x,y,z) x+y-z/2
fctn2(1,2,3)
## [1] 1.5
#Simple plots
plot(sin, -pi, 2*pi)   #plot the curve of y=sin(x) from -pi to 2 pi

square <- function(x) x*x   #Define a function
plot(square, -3,2)   # Plot the defined function

# Plot a 3D surface
x <- seq(-1, 1, length=100)
y <- seq(-1, 1, length=100)
z <- outer(x, y, function(x, y)(1-x^2-y^2))  
#outer (x,y, function) renders z function on the x, y grid
persp(x,y,z, theta=330)