Chapter 1 Introduction To R
Chapter 1 Introduction To R
Chapter 1 Introduction To R
1+ 2
2
◎
3+ 4
> ((1+2)/(3+4))^2
[1] 0.1836735
Please do Exercise 1
Part II
VECTORS
Contents
1. Create Vectors
2. Vector Arithmetic
Create Vectors
1) Use function c( ).
◎The function c( ), known as the catenate or
concatenate function, can be used to create
vectors from scalar or other vectors.
◎Examples:
> x<-c(1,3,5,7) #create vector x from single
numbers/ scalars
> y<-c(2,4,6,8) #create vector y from single
numbers/ scalars
> z<-c(x,y) #create vector z from vector x and
vector y
Create Vectors
2) Use colon operator “:”.
◎The colon coperator can be used to generate
sequence of numbers which increase or decrease
by 1.
◎Examples:
> 1:10 #increasing sequence
> 10:1 #decreasing sequence
Create Vectors
3) Using the function seq( ).
◎The function seq( ) can be used to sequence of numbers starting
and stopping at specified values with increments defined by user.
◎This function contains 3 arguments, the first argument is the
starting point, the second argument is the stopping point and the
last argument is the increment.
◎Examples:
> seq(0,1,0.1) # values between 0 and 1 with an increment of 0.1
> seq(0,200,50) #values between 0 and 200 with an increment
of 50
> seq(20,5,-4) #values between 5 and 20 with an increment of -
4. The sequence is in decreasing order.
Create Vectors
4) Using the function rep( ).
◎The function rep( ) stands for repeat or replicate.
◎The function contains 2 arguments, the first argument is a
value or a vector, the second argument is the number of times
the value or each element of the vector (in the first argument) is
replicated.
◎Examples:
> rep(3,5) #repeat the number '3' five times
> rep(c(1,3,6,9),3) #repeat the vector 3 times
> a<-c(2,3,4); rep(a,4) #repeat vector a 4 times
> rep(1:3,2) #repeat sequence 2 times
> rep(1:3, c(2,2,2)) #repeat each element of sequence 2 times
Vector Arithmetic
◎The same functions used for scalars can be used
on vectors.
◎However, the length of the vectors must be
carefully observed or some vector arithmetic will
result in errors.
◎The square brackets [ ] are used to identify
specific elements in vectors.
◎Logical operators could also be used on vectors.
Vector Arithmetic
◎Some useful functions for vectors are as follows:
Functions Details
length() The size of the vector
sum() Calculates the total of all values in the
vector
prod() Calculates the product of all values in the
vector
cumsum(), cumprod() Calculates the sumulative sums or products
in the vector
sort() Sort the values in the vector
diff() Computes the differences (with lag 1 as
default)
Vector Index
◎Use to retrieve members of a vector
◎Example:
> x<-c(3,2,5,7,1)
> x[3]
[1] 5
> x[-2]
[1] 3 5 7 1
> x[c(1,4,2)]
[1] 3 7 2
> x[x<=3]
[1] 3 2 1
Part III
MATRICES
Contents
1. Create Matrices
2. Matrix Operations
Create Matrices