R Training by Emma Mba
R Training by Emma Mba
R Training by Emma Mba
http://cran.r-project.org/bin/windows/base/
www.r-project.org
Help Facilities
There are many choices to start the help system :
– To know the mode of any object use mode ( )
function
Types of data objects
There are seven basic types of data objects in R:
Vector ( a set of values) – one way array of data.
Matrix (two way array).
Array ( a matrix with more than two dimensions)
Data frame ( generalized matrices that allow a mix
of columns with different data modes).
Factor (categorical data).
List ( a list of components, where each component
can be a data object of different data types).
Time series.
Operators in R
Example 1:
== Equal to ! Not
greater than or
>= != Not equal to
equal to
Less than or equal
<=
to
III. Logical and comparison operators
Example 2:
> 3<4
[1] TRUE
> 3==4
[1] FALSE
> x<2
[1] TRUE TRUE TRUE TRUE TRUE FALSE FALSE
> sum(x<2)
[1] 5
sum(x>=2)
[1] 2
Missing values
NA
Example 3:
> 0/0 > Inf - Inf
[1] NaN [1] NaN
> log(-2)
>Inf/Inf [1] NaN
[1] NaN Warning message:
NaNs produced in: log(x)
Missing values
The function is.na(x) gives a logical vector of the same size as x with value TRUE if and
only if the corresponding element in x is NA.
> x<-c(1:3,NA) ; x
[1] 1 2 3 NA
> is.na(x)
[1] FALSE FALSE FALSE TRUE
> sum(x)
[1] NA
> x[!is.na(x)]
[1] 1 2 3
Missing values
> x<-c(1,2,3,NaN,4,5,NaN,7); x
[1] 1 2 3 NaN 4 5 NaN 7
> is.na(x)
[1] FALSE FALSE FALSE TRUE FALSE FALSE TRUE FALSE
> sum(x)
[1] NaN
Use of Brackets
Name of
bracket function
bracket
A. Creating a vector
function Symbol description example
Combines
Concatenate c( ) values with Xc(2,3,8,0,-7)
command
any mode
seq(from= ,to= ,by= ) Regular X seq(1,10,1)
Sequence
sequences of
command : to X1:10
from numbers
Takes a
Replicate rep(x, times= ) pattern and Xrep(1, 5)
command
replicates it
DATA STRUCTURE
I. Vector
A. Creating a vector
Example 4:
> c(1,7:9)
[1] 1 7 8 9
DATA STRUCTURE
I. Vector
Example 5:
> 1:4
[1] 1 2 3 4
> seq(1,9, by = 2)
[1] 1 3 5 7 9
> seq(1,by=0.05,length=10)
[1] 1.00 1.05 1.10 1.15 1.20 1.25 1.30 1.35 1.40 1.45
DATA STRUCTURE
I. Vector
Example 6:
> rep(1:4, 2)
[1] 1 2 3 4 1 2 3 4
> x*2
[1] 2 4 6 8 10 12 14 16 18 20
> y<-6:2
>y
[1] 6 5 4 3 2
> y+x
[1] 7 7 7 7 7 12 12 12 12 12
DATA STRUCTURE
I. Vector
C. Accessing elements in a vector
> log(y[y>0])
[1] 0.0000000 0.6931472 1.0986123
> z=c(2,5,4,NA,3,-2)
> z[!is.na(z)]
[1] 2,5,4,3,-2
> mean(z[!is.na(z)])
[1] 4.5
DATA STRUCTURE
I. Vector
C. Accessing elements in a vector
>X
[1] 2 4 6 8 10
> X[2]
[1] 4
You also could use rep( ) or seq( ) inside []
> X[seq( )];X[rep( )]
Some Arithmetic and Statistical R Functions
R Function Notes
log(x), log10(x), exp(x), sqrt(x) ln(x), log10(x), ex, x
Sin(x), cos(x), tan(x) Trigonometric function
Maximum, minimum, number of elements, and range of a
max(x), min(x), length(x), range(x)
vector
Sign, absolute value, sort in ascending order, summation,
sign(x), abs(x), sort(x), sum(x), prod(x)
product of elements in a vector x
ceiling(x) Rounds to the next higher integer
floor(x) Rounds to the next lower integer
trunc(x) Cuts off all digits after the decimal point
Rounds to the nearest integer. The second argument is the
round(x), round(x, 3), round(x, -1) number of significant number of digits desired, negative
value to round large number to nearest 10 or 100, etc.
cor(x,y), mean(x), var(x), quantile(x),
Statistical function
median(x), summary( ),
Quotient( integer division), modulo function (remainder)
%/%
% / % and % % always satisfy e1 = = ( e1 % / % e2))e2+e1 %
%%
% e2
Returns an object which, for each element, is the sum
cumsum(x), cumprod(x)
(product) of all of the elements to that point.
gamma Gamma function
Statistical function in R
Measures Function in R
Mean mean(x)
Median median(x)
range(x)
return vector of two elements (min(x),max(x))
Range the actual range
range(x)[2] – range(x)[1]
or diff(range(x))
Variance var(x)
> x<-log(y); x
Warning message:
NaNs produced in: log(x)
[1] NaN 0.6931472 NA 1.6094379 1.3862944
> mean(x)
[1] NA
A. Creating matrix
matrix(1:12,3,4)
Creates matrix, takes a vector argument and turns
matrix(1:12,3)
matrix( ) it into a matrix
matrix(1:12,ncol=4)
matrix(data, nrow, ncol, byrow = F)
matrix(1:12,3,4,byrow=T)
B. Matrix arithmetic
Function Description
nrow( ), ncol( ) Returns the number of row or the column of the matrices
dimnames( ) Returns or changes the dimnames attribute of a matrix or array
Either creates a diagonal matrix or extracts the diagonal
diag( )
elements of a matrix
Solve( ) Calculate the inverse
var( ) Covariance matrix of the columns
t(x) Transpose of x
eign(x) Eigenvalues and eigenvectors of x
apply( ) Applies a function to each row or column in the matrix
data.frame(data1,data2,…)
> car.inf$model
[1] Proton Saga Werra
> car.inf[1,2]
[1] 27
DATA STRUCTURE
IV. List
A list allows a programmer to tie together related
data that do not have the same structure (different
lengths or modes).
A) Creating List:
Used list() function.
B) List Indexing:
To access the elements in a list, used a double square
brackets [[ ]] then the sub elements by using a single
square brackets.
DATA STRUCTURE
IV. List
Example 16:
Create a list with two components: car.inf data frame and no.model
vector
> no.model<-c(1990,2002,2005)
> car.list<-list(car.inf,no.model); car.list
[[1]]
model price
1 Proton 27
2 Saga 25
3 Werra 20
[[2]]
[1] 1990 2002 2005
DATA STRUCTURE
IV. List
> names(car.list)<-(c("car.inf","no.model"))
> car.list[[1]]; car.list$car.inf;
model price
1 Proton 27
2 Saga 25
3 Werra 20
A) if ( condition ) { expression 1 }
B) if ( cond 1 ) { expr 1 }
else if ( cond 2 ) { expr 2 }
else { last expr }
C) ifelse ( condition, expression for true,
expression for false )
Example 24:
Programming Tools
III.Writing Function
Syntax:
function_name <- function ( input arguments )
{
function body ( R expressions )
return ( list ( output argument ))
}
You can call the function using the calling routine
function_name ( argument )
Programming Tools
III.Writing Function
Note that:
1. All variables declared inside the body of a
function are local and vanish after the
function is executed.
2. Better to use return function if we need more
than one value to return from function.
Programming Tools
III.Writing Function
Example 25:
1) Construct a function which determines the
sign of number.