R Code for Climate Mathematics:

Theory and Applications

 

A Cambridge University Press book By

SSP Shen and RCJ Somerville

 

 

Version 1.0 released in July 2019 and coded by Dr. Samuel Shen, Distinguished Professor
San Diego State University, California, USA
https://shen.sdsu.edu
Email:

 

Version 2.0 compiled and updated by Momtaza Sayd
San Diego State University May 2021
Version 3.0 compiled and updated by Joaquin Stawsky
San Diego State University June 2022

 

 

 

Chapter 2: Basics of R Programming

R as a smart calculator

1+4
## [1] 5
2+pi/4-0.8
## [1] 1.985398
x <- 1
y <- 2
z <- 4
t <- 2*x^y-z
t
## [1] -2
u = 2        # "=" sign and "<-" are almost equivalent
v = 3        # The text behind the "#" sign is comments
u+v
## [1] 5
sin(u*v)    # u*v = 6 in the sine function is considered a radian by R 
## [1] -0.2794155

 

Define a sequence in R

#Enter temperature data in c() 
tmax <- c(77, 72, 75, 73, 66, 64, 59)
#Show the data
tmax
## [1] 77 72 75 73 66 64 59
#Generate same sequence using different methods
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 in R

#Define a function
samfctn <- function(x) x*x
samfctn(4)
## [1] 16
fctn2 <- function(x,y,z) x+y-z/2
fctn2(1,2,3)
## [1] 1.5

 

Plot with R

#Plot temperature data
plot(1:7, c(77, 72, 75, 73, 66, 64, 59))

#More plot examples
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)