R tutorial

About R

R is a free software environment for statistical computing and graphics.

Open R

Data types

We can use variables without definition in advance

numbers

num=3.14;
print(num)
## [1] 3.14
print(num+1)
## [1] 4.14
print(typeof(num))
## [1] "double"
num.int=as.integer(num);
print(num.int)
## [1] 3
print(typeof(num.int))
## [1] "integer"
x=2;
print(x*2);
## [1] 4
print(log(x));
## [1] 0.6931472
print(sqrt(x));
## [1] 1.414214
print(x**3);  
## [1] 8

array

x=10:12;
print(x);
## [1] 10 11 12
y=c(1,3,5);
print(y);
## [1] 1 3 5
print(y[1])
## [1] 1
matrix=cbind(x,y);
print(matrix);
##       x y
## [1,] 10 1
## [2,] 11 3
## [3,] 12 5
print(matrix[2,])
##  x  y 
## 11  3
print(matrix[c(2,3),])
##       x y
## [1,] 11 3
## [2,] 12 5
print(matrix[matrix[,1]<12,])
##       x y
## [1,] 10 1
## [2,] 11 3
print(matrix[,2])
## [1] 1 3 5

data frame \(\it\bf\color{red}{(Important)}\)

df=data.frame(x=x,y=y);
print(df)
##    x y
## 1 10 1
## 2 11 3
## 3 12 5
print(df$x);
## [1] 10 11 12
print(df$y);
## [1] 1 3 5

Packages

Install

install.packages('fields')

Load

library(fields)

Basic plots

Use function “plot”

x=1:1000/10;
y=sin(x);
print(x[1:10]);
##  [1] 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1.0
print(y[1:10]);
##  [1] 0.09983342 0.19866933 0.29552021 0.38941834 0.47942554 0.56464247
##  [7] 0.64421769 0.71735609 0.78332691 0.84147098
plot(x,y)

plot(x,y,type='l')

plot(x[1:20],y[1:20],type='b',col='red',lwd=5,ylim=c(0,2))

Use function “histogram”

set.seed(2017)
rand=rnorm(1000);
set.panel(1,2);
## plot window will lay out plots in a 1 by 2 matrix
plot(rand,type='l');
hist(rand)

help(hist)

help(quantile)

Calculate the \(5\%\) percent quantile, median, and \(95\%\) percent quantile as follows.

##          5%         50%         95% 
## -1.59585243  0.01210508  1.60853804

Use function “quilt.plot”

quilt.plot is function in package “fields” to produce an image-like plot

library(fields)
data(ozone2)
plot(ozone2$lon.lat[,1],ozone2$lon.lat[,2],xlab='lon',ylab='lat')
US( add=TRUE, col="grey", lwd=2)

quilt.plot( ozone2$lon.lat, ozone2$y[16,],xlab='lon',ylab='lat')
US( add=TRUE, col="grey", lwd=2)