Baic programming in R:
R is a vector based language not needing loops which we use in languages such as C, C++, MATLAB etc. Lets take an example of adding two vectors together and put the result in a vector z.
# Defining the vectors
x<-c(1,2,3,4)
y<-c(5,6,7,8)
Vector addition using loop:
# Starting with a blank vector z
z<-c()
for(i in 1:4){z<-c(z,x[i]+y[i])}
z
## [1] 6 8 10 12
But R is a “vectorized programming language” unlike the “de vectorized approach”.
So, instead of using loop for addition, we just add them as vectors.
Addition without loop:
z<-x+y
z
## [1] 6 8 10 12
We could do different calculations on the vectors such as multiplication, division etc.
Functions in R:
What if we needed to create our own function, though, we do not need to create a function here but later on if we wanted to create, we could use this approach.
square<-function(a,b) a+b
z<-square(x,y)
z
## [1] 6 8 10 12
Recycling of vectors:
If the vectors are of different lengths:
Approach 1:
One vector is multiple of the other.
# x will be recycled as (1,2,1,2) to reach the dimentionality of y.
x<-c(1,2)
y<-c(5,6,7,8)
z<-x+y
z
## [1] 6 8 8 10
Approach 2:
One vector is not a multiple of the other, R will give us a warning.
# R does recycling here too but it will repeat the first element after reaching the end of the vector x to match y.
x<-c(1,2,3)
y<-c(5,6,7,8)
z<-x+y
## Warning in x + y: longer object length is not a multiple of shorter object
## length
z
## [1] 6 8 10 9