You are on page 1of 23

Introduction to R

Prof. Dilip Kumar

DILIP KUMAR
Outline
Basic operations (Arithmetic, Logical and Relational)
Creating vectors and matrices and related operations
Importing data in R
Exporting results in a file
Conditional statement
Loop
User defined functions

DILIP KUMAR
R-Studio

DILIP KUMAR
Working in command window
Type a command next to >
Writing comments
Use # symbol in the beginning of line.
To clear the command window: Press Ctrl+L.
To clear all variables, use rm(list=ls())

DILIP KUMAR
Setting a working directory
Use a command:
> setwd(directory path)
> setwd(C:/R_Workshop)

DILIP KUMAR
Arithmetic operators
Addition = A + B
Subtraction = A - B
Multiplication = A * B
Division = A / B
Exponentiation = A ^ B
Remainder from division= A %% B
Quotient of division = A %/% B
Matrix multiplication = A %*% B
Transpose of matrix = t(matrix)
Inverse of matrix = solve(A)

DILIP KUMAR
Relational operators
Less than = A < B
Greater than = A > B
Less than and equal to = A <= B
Greater than and equal to = A >= B
Equal to = A == B
Not equal to = A != B
The results will be either TRUE or FALSE. To get numeric value of
the result, use > as.numeric(A<B)
1 means TRUE and 0 means FALSE
Assignment operator (Left)= A = B or A <- B or A<<-B
Right assignment operator = A -> B or A ->> B
Assignment operator (A = B) indicates that the value of B is assigned
to A.

DILIP KUMAR
Logical operators
Logical AND = A && B
Element wise AND = A & B
Logical OR = A || B
Element wise OR = A | B
NOT = !A

Note
Non-zero number is considered as true and zero as false.
Mainly used with conditional statement (if)

DILIP KUMAR
Order of precedence
()
^
* and /
+ and -

DILIP KUMAR
Elementary math functions
> a = sqrt(x) //find square root of x.
> a = exp (x) //find exponential of x
> a = log (x) //find natural logarithm of x
> a =log10(x) //base 10 logarithm
> a = log2(x) //base 2 logarithm
> a = log(x)/log(m) // base m logarithm
> a = factorial(x) / / x!
> a = abs(x) //find absolute value of x
> a = round (x) //round to nearest integer
> a = sign (x); //return sign of the number (for zero, it
returns 0, -1 for negative and 1 for positive)

DILIP KUMAR
Creating vectors
A vector can be created:
A = c(1,2,3,4)
We can combine different vectors also. For example a and
b are two vectors and we want to combine them. Use
z = c(a,b)
A = 1:10 or a = seq(1,10) // It is a vector of elements from 1
to 10 with increment of 1, i.e., [1 2 3 4 5 6 7 8 9 10]
A = seq(First element, Last element, length=No. of elements)
A = seq(1,10,length=20)
A = seq(First element, Last element, by=increment)
A = seq(1,10,by=2)
Creating vectors by repeating elements.
>z = rep(0,10) // a vector will contain ten zeros
>z = rep(1:3,2) // a vector will look like [1 2 3 1 2 3]
DILIP KUMAR
Addressing vector elements
A vector element is addressed in R with an integer
index enclosed in square braces [ ]. For example:
Addressing single element:
> A[2] % will provide 2nd element of the vector.
Addressing block of elements: Use colon notation, i.e.,
(start : end).
> A[2:5] %will provide 2nd, 3rd, 4th and 5th elements.
> A[c(1,4,6)] % will provide 1st, 4th and 6th element
> A[seq(2,10,by=2)] % will provide 2nd, 4th, 6th, 8th and 10th
elements.
Removing particular element from the vector
>a[-2] % will remove second element of vector a.
Length of vector: length(a)
DILIP KUMAR
Creating Matrix
We can create matrix by:
A = matrix(elements, nrow=x,ncol=y) //This will create a
matrix of elements with x rows and y columns.
>A = matrix(1:9,nrow=3,ncol=3) //columns are filed in sequence
>A = matrix(1:9,nrow=3,ncol=3, byrow=TRUE) //row-wise
Combining vectors (columns) to make matrix: use cbind
z=cbind(a,b,c,d) //where a,b,c and d are vectors
Combining vectors (rows) to make matrix: use rbind
z=rbind(a,b,c,d)
Creating empty matrix:
z=matrix(nrow=3,ncol=3)
Addressing matrix: uses two dimensions (row, col)

DILIP KUMAR
Addressing elements in a matrix
Use matrix_name[row, column].
Use nothing to address entire row or column.
Forexample: > A [,2] %Display elements of (all rows)
column 2.
>> A [2, ] %Display elements of row 2 (all columns).
>> A[2,3] % Display an element at row 2 and column 3.

DILIP KUMAR
Importing data
Importing data (as a dataframe)
From csv file:
data1=read.table(C:/./Gold_data.csv", header=T, sep=",")
The imported data is in the form of dataframe
To access a particular column in a data, use data_name$col_name
For example: z=data2$Nifty

DILIP KUMAR
Exporting data
To csv file
write.table(result_var, C:/./result.csv", sep=,")
To text file
write.table(result_var, C:/./result.txt")

DILIP KUMAR
User Inputs
Use readline command. The input will be considered as
string or character.
> var_name=readline(Enter the choice=)

To convert this string input to numeric input, use the


following command:
as.numeric(var_name)

DILIP KUMAR
Conditional statement (if ..)
Syntax:
if (test expression){
statement
}

Example:
rm(x,a) # remove variables x and a from memory
x=0 # initializing x to be zero
a=runif(1) #Uniform random number (one number)
if (a<0.5){
x=-1
}
x
DILIP KUMAR
Conditional statement (if else)
Syntax if (test expression){
statement 1
} else {
statement 2
}
Example:
rm(x,a)
a=runif(1) #Uniform random number
if (a<0.5){
x=-1
} else {
x=1
}
x

DILIP KUMAR
Conditional statement (if else if - else)
Syntax if (test expression 1){
statement 1
} else if (test expression 2){
statement 2
} else {
statement 3
}

Example: rm(x,a)
a=runif(1) #Uniform random number
if (a<0.5){
x=-1
} else if (a==0.5){
x=0
} else {
x=1
}
x
DILIP KUMAR
For loop
Syntax for (val in sequence) {
statement
}
Examples:
rm(list=ls())
a=0;
for (i in 1:10)
{
a[i]=i*5
}
a

DILIP KUMAR
Finding moving average of returns using
loop
#Finding Moving average of returns
rm(list=ls())
data=read.table("Gold_data.csv",header=T,sep=",")

nifty=data$Nifty
ret=diff(log(nifty))*100

l=length(ret)
m=5
mov_av=0

for (i in 1:(l-m+1)){
mov_av[i]=mean(ret[i:(i+m-1)])
}

DILIP KUMAR
User defined functions
Syntax
func_name <- function (argument) {
statement
}
Examples:

# Function to simulate random walk


#Function to add two numbers
rand_walk<-function(n){
fun1<-function(a,b){
x=rnorm(n)
c=a+b
y=cumsum(c(0,x))
return (c)
plot(1:(n+1),y,"l")
}
}

DILIP KUMAR

You might also like