top of page
Writer's pictureAdisorn O.

Basic in R Programming

Updated: Jun 3, 2023



R is currently one of the most popular languages for data analysis among Python, MATLAB, and Java. It is highly capable of statistical analysis, simulation, and machine learning applications. It provides a user-friendly environment like MATLAB and Python while maintaining a structured programming style with robust analysis and visualization tools. It's very efficient to use R in generating deep learning network models because of its capacity to handle large datasets. As an open-source project, R has unlimited possibilities for future extensions to match specific needs for real-world applications.


Syntax:


# Basic in R

# Vector

v1 = c(1, -1, 1, -1)

v2 = c(2, -2, 2, -2)

v1+v2


[1] 3 -3 3 -3


v1*v2

[1] 2 2 2 2


# Matrix

matrix(0,3,3) # similar to zeros(3) in MATLAB

[,1] [,2] [,3]

[1,] 0 0 0

[2,] 0 0 0

[3,] 0 0 0


v1 = c(1,-1,1)

v2 = c(2,-2,2)

v3 = c(3,-3,3)


cbind(v1,v2,v3) # ordering vector by column to a matrix

v1 v2 v3

[1,] 1 2 3

[2,] -1 -2 -3

[3,] 1 2 3


rbind(v1,v2,v3) # ordering vector by row

[,1] [,2] [,3]

v1 1 -1 1

v2 2 -2 2

v3 3 -3 3


# Linear system and solve()

A = matrix(c(1,-2,3, 2,4,2, 3,3,6),3,3)

b = c(1,-1,2)


A[1,3] # access element (1,3)

[1] 3


invA = solve(A) # inverse A


solve(A,b) # solve Ax = b to avoid matrix inversion

[1] 1.0000000 0.5000000 -0.3333333


invA %*% b # matrix multiplication using %*%

[,1]

[1,] 1.0000000

[2,] 0.5000000

[3,] -0.3333333


t(A) # transpose A

[,1] [,2] [,3]

[1,] 1 -2 3

[2,] 2 4 2

[3,] 3 3 6


# Define function in R

add = function(x1,x2) {

x1+x2

}


add(2,3)

[1] 5


# Conditions 1

a =1

b =2


if(a<b){

print("a<b")

}else {. # else must be in the same line with curly bracket

print("a>b")

}

[1] "a<b"


# Conditions 2

x = rnorm(1)

if(x>1){

print ("greater than 1")

}else if(x<1 & x > 0 ) {

print("less than 1")

}else{

print("less than zero")

}

[1] "greater than 1"


# while Loops

i = 1


while(i<10){

print(i)

i = i+1

}

[1] 1

[1] 2

[1] 3

[1] 4

[1] 5

[1] 6

[1] 7

[1] 8

[1] 9


#For loop

for(i in 1:10){

print(i)

}

[1] 1

[1] 2

[1] 3

[1] 4

[1] 5

[1] 6

[1] 7

[1] 8

[1] 9

[1] 10


# Homework 1

# Proof the law of large numbers

rsum = 0


rsum2 = 0


n1 = 0


n = 0


r = rnorm(1000)


for(i in r){

rsum = rsum+i

n = n+1

if(i < 1 & i > 0){

n1 = n1+1

}

}


# E(r)

rsum/n

[1] -0.02844646


# P(-1<x<1)

n1/n*2

[1] 0.672


Resources:


R's webpage


How to download and install R-studio (DDS):


R programming for Beginners (DDS):


Matrix Operations in R:


(To be continued)

13 views
bottom of page