Skip to main content

R Programming 2

 

R Programming 2

In this lab of R programming, we will go through various operations such as creating functions, loops, connecting to data base, graphics, etc.

While Loop (try the following in R):

x = 0
while ( x < 10 )
 {
   x = x + 1
    print(x)
 }
## [1] 1
## [1] 2
## [1] 3
## [1] 4
## [1] 5
## [1] 6
## [1] 7
## [1] 8
## [1] 9
## [1] 10

For Loop (try the following in R):

x = 1:3
for ( i  in  x ) {
 print( i^2)
}
## [1] 1
## [1] 4
## [1] 9
#Printing up to 20th Fibonacci number  (try the following in R):
x = 0               #We are starting from 0
y = 1               #Second in the sequence
fn  = vector("numeric", 20)     #Empty numeric vector to store all values

for ( i  in  2:20) {
if(i==2)fn[1:2] = c(x,y) else fn[i] = k
k = x + y
x = y
y = k
}

fn
##  [1]    0    1    1    2    3    5    8   13   21   34   55   89  144  233  377
## [16]  610  987 1597 2584 4181
# Printing a table  (try the following in R):
for (i in 1:20){
 cat(i,"*",15,"=",i*15,"\n")
}
## 1 * 15 = 15 
## 2 * 15 = 30 
## 3 * 15 = 45 
## 4 * 15 = 60 
## 5 * 15 = 75 
## 6 * 15 = 90 
## 7 * 15 = 105 
## 8 * 15 = 120 
## 9 * 15 = 135 
## 10 * 15 = 150 
## 11 * 15 = 165 
## 12 * 15 = 180 
## 13 * 15 = 195 
## 14 * 15 = 210 
## 15 * 15 = 225 
## 16 * 15 = 240 
## 17 * 15 = 255 
## 18 * 15 = 270 
## 19 * 15 = 285 
## 20 * 15 = 300
#cat() is another function in R for printing, it allows concatenating of values and characters
# "\n" is used to seperate the lines while printing

Conditional Statements (try the following in R):

x = 11

 if(x != 11){print("I have not understood loops")
 } else print("I understood loops")
## [1] "I understood loops"
#Always start “else” just next to the closing curly bracket of “if” statement
#If it is one line code then both “if” and “else” must be in one line 


if(x==11) x else x+2                #Example of one line if else statement
## [1] 11
if(x>5){ if(x>11)print(x)else print(x*2)        #Example of nested if-else
    }else print(x^2) 
## [1] 22
#Try different values of x (11, 12, 3) and see the results for the above nested if else

Exercise: Try the following:

x = 3; y = 1 Write if-else statements while using x and y both in if condition to print the x*y and x/y. You can use two if-else or just one; the choice is yours.

Hint: There are multiple options to print the same result. The idea is to make you practice.

Function (try the following in R):

square = function(a){               #Function to return the square of a number
               b = a*a
               b}           

square(3)                   #example of calling the function
## [1] 9

Exercise: Try the following:

Write a function that returns a polynomial up to degree 3. Your function must print the supplied value, its square and its cube. You can name it pol3. Hint: you can use ^ or ** for raising the power of a value by n degree.

adn2  = function(x,y){      #Addition of two values or vectors of same length
    ad = x + y
    ad}

#Try the following examples for above function: adn2(3,4) or adn2(c(1,2), c(3,4))

ad_mul  = function(x,y){        
        ad = x + y      
        mul = x*y       
        list(ad=ad, mul=mul)}   

#The above Function performs two operations: addition and multiplications and returns two values using list()

am = ad_mul(3,4) #Calling the function for x as 3 and y as 4 

names(am)           #displays the names of values returned by the function
## [1] "ad"  "mul"
am$ad               #returns the value of ad
## [1] 7
am$mul          #returns the value of mul
## [1] 12
#Try all of the above in your R

f1  = function(x, y, f){
    f(x, y)
        }           #Using a function within another function
f1(3,4,ad_mul)
## $ad
## [1] 7
## 
## $mul
## [1] 12
save(f1, file = "f1.R")             #To save the function in your working directory
load("f1.R")                #To load the function in your R session

Exercise: Try the following:

Write a function that returns up to kth Fibonacci number.

Hint: Inside your function, you can use the example of Fibonacci number provided in the for loop section of this lab. The function must return up to kth Fibonacci number instead of 20th number. Your function should work for any value of k>=2.

##Connecting to a database/server and running queries (need access to a database/server):

library(RODBC)                  #Package required for the operation

# odbcConnect() function allows us to log on to the server, (you need login credentials)
connection <- odbcConnect(dsn="servername",uid="userid",pwd="******") 

#Define the query as a string/character/text in “ “ marks
query <- "SELECT * FROM table WHERE ..."

# sqlQuery() allows us to run a query on a database on a server
myData <- sqlQuery(connection, query, errors=TRUE)

odbcClose(connection) #This closes the connection

Graphics (try the following in R):

plot() is a scatterplot function to plot a graph

Type ?plot in R to know more details on this function

x = 1:5
y = c(4,1,3,6,8)

plot(x, y)              #plots only datapoints

plot(x, y, type = "l")          #plots the line joining datapoints

plot(x, y, type = "o")          #plots datapoints along with the line joining them 

plot(x, y, main= "example", xlab= "some X",
                   ylab= "someY ", col= "red")

points(3,4, col= "blue", pch=4)         #Adding a point with color= blue and shape pch = 4

points(2,4, col= "green", pch=6)    #Adding a point with color= green and pch = 6

text(3, 5, "my name")           #Adding text to the plot

Exercise: Try the following:

Try different values of x and y and use all the plot options provided above. Also try different colors and shapes (pch values).

More graphics (try the following in R):

hist() is used to plot histogram

barplot() is used to plot bar chart

pie() is used to plot pie chart

Type ?hist or ?barplot or ?pie in R to know more details on these functions

Example:

par(mfrow=c(2,2))   #to split graphic window for multiple plots at a time (here it is 4)

hist(c(1:10,3:5,4:6))

x = c("red", "red", "blue", "green")

t = table(x)        #character variable as table for pie chart or bar plot 

barplot(t)

pie(t)

Exercise: Try the following:

  • x = c(“red”, “blue”, “green”, “red”, “orange”, “yellow”, “white”)
  • y = c(“car1”, “car2”, “car2”, “car1”, “car3”, “car4”, “car2”)
  • t = table(x, y)

Use barplot() to plot bar chart using col=x for color in the function. Try to interpret the meaning of the chart.

Saving graphics as files on your system (try the following in R):

#graphs can be saved as .pdf, .ps, .bmp, .png by opening respective devices:
pdf("plot1.pdf")
x = c(1,2,3:10,9, 11:30)
y=log(x)
plot(x, y)
graphics.off()

postscript("plot1.ps")
x = c(1,2,3:10,9, 11:30)
y=log(x)
plot(x, y)
graphics.off()

png("plot1.png")
x = c(1,2,3:10,9, 11:30)
y=log(x)
plot(x, y)
dev.off()
## null device 
##           1
bmp("plot1.bmp")
x = c(1,2,3:10,9, 11:30)
y=log(x)
plot(x, y)
graphics.off()

You can use either dev.off() or graphics.off() to close the graphics device

exists("iris")          # Iris flower built-in dataset in R 
## [1] TRUE
dim(iris)           #To check the dimension; it has 150 records and 5 variables
## [1] 150   5
names(iris) #To view the variable names, length and width of sepal and petal and species
## [1] "Sepal.Length" "Sepal.Width"  "Petal.Length" "Petal.Width"  "Species"
#We will use scatterplot3d package to generate 3-D plot of the data

library(scatterplot3d)

scatterplot3d(iris$Petal.Width, iris$Sepal.Length, iris$Sepal.Width) 

#This gives a static plot

#We will use rgl package to generate 3-D plot of the data

library(rgl)

plot3d(iris$Petal.Width, iris$Sepal.Length, iris$Sepal.Width)

#This generates a 3-D plot that can be rotated in different angles (left-click the plot and move your mouse or you can use your touchpad as well)

If you are unable to install these two 3-d packages, don’t worry about them.

Using package MASS and Base R for datasets (try the following in R):

library(MASS)           #This comes with R and has many datasets and functions

ls(pos="package:MASS")  #To display the entire content of a package within workspace
##   [1] "abbey"             "accdeaths"         "addterm"          
##   [4] "Aids2"             "Animals"           "anorexia"         
##   [7] "area"              "as.fractions"      "bacteria"         
##  [10] "bandwidth.nrd"     "bcv"               "beav1"            
##  [13] "beav2"             "biopsy"            "birthwt"          
##  [16] "Boston"            "boxcox"            "cabbages"         
##  [19] "caith"             "Cars93"            "cats"             
##  [22] "cement"            "chem"              "con2tr"           
##  [25] "contr.sdif"        "coop"              "corresp"          
##  [28] "cov.mcd"           "cov.mve"           "cov.rob"          
##  [31] "cov.trob"          "cpus"              "crabs"            
##  [34] "Cushings"          "DDT"               "deaths"           
##  [37] "denumerate"        "dose.p"            "drivers"          
##  [40] "dropterm"          "eagles"            "enlist"           
##  [43] "epil"              "eqscplot"          "farms"            
##  [46] "fbeta"             "fgl"               "fitdistr"         
##  [49] "forbes"            "fractions"         "frequency.polygon"
##  [52] "GAGurine"          "galaxies"          "gamma.dispersion" 
##  [55] "gamma.shape"       "gehan"             "genotype"         
##  [58] "geyser"            "gilgais"           "ginv"             
##  [61] "glm.convert"       "glm.nb"            "glmmPQL"          
##  [64] "hills"             "hist.FD"           "hist.scott"       
##  [67] "housing"           "huber"             "hubers"           
##  [70] "immer"             "Insurance"         "is.fractions"     
##  [73] "isoMDS"            "kde2d"             "lda"              
##  [76] "ldahist"           "leuk"              "lm.gls"           
##  [79] "lm.ridge"          "lmsreg"            "lmwork"           
##  [82] "loglm"             "loglm1"            "logtrans"         
##  [85] "lqs"               "lqs.formula"       "ltsreg"           
##  [88] "mammals"           "mca"               "mcycle"           
##  [91] "Melanoma"          "menarche"          "michelson"        
##  [94] "minn38"            "motors"            "muscle"           
##  [97] "mvrnorm"           "nclass.freq"       "neg.bin"          
## [100] "negative.binomial" "negexp.SSival"     "newcomb"          
## [103] "nlschools"         "npk"               "npr1"             
## [106] "Null"              "oats"              "OME"              
## [109] "painters"          "parcoord"          "petrol"           
## [112] "phones"            "Pima.te"           "Pima.tr"          
## [115] "Pima.tr2"          "polr"              "psi.bisquare"     
## [118] "psi.hampel"        "psi.huber"         "qda"              
## [121] "quine"             "Rabbit"            "rational"         
## [124] "renumerate"        "rlm"               "rms.curv"         
## [127] "rnegbin"           "road"              "rotifer"          
## [130] "Rubber"            "sammon"            "select"           
## [133] "Shepard"           "ships"             "shoes"            
## [136] "shrimp"            "shuttle"           "Sitka"            
## [139] "Sitka89"           "Skye"              "snails"           
## [142] "SP500"             "stdres"            "steam"            
## [145] "stepAIC"           "stormer"           "studres"          
## [148] "survey"            "synth.te"          "synth.tr"         
## [151] "theta.md"          "theta.ml"          "theta.mm"         
## [154] "topo"              "Traffic"           "truehist"         
## [157] "ucv"               "UScereal"          "UScrime"          
## [160] "VA"                "waders"            "whiteside"        
## [163] "width.SJ"          "write.matrix"      "wtloss"
help(package="MASS") #This displays the content of a package in a separate page
data(package="MASS")        #To view the datasets in a package

# Additionally, base R itself offers many datasets for our use and practice:

library(help = "datasets")  #To view the datasets in R
women           #Example of dataset in R
##    height weight
## 1      58    115
## 2      59    117
## 3      60    120
## 4      61    123
## 5      62    126
## 6      63    129
## 7      64    132
## 8      65    135
## 9      66    139
## 10     67    142
## 11     68    146
## 12     69    150
## 13     70    154
## 14     71    159
## 15     72    164

You can use datasets provided in MASS package and Base R for your practice in this section as well as in the later sections.


Click the links below for more

Comments

Popular posts from this blog

Support Vector Machine in R

  Lab_SVM_1_RM Asmi Ariv 2022-10-04 Support Vector Machine in R In this lab, we will learn how to use Support Vector Machine in R to build a classifier. Kindly go through the video lectures to get a better understanding of this lab. We will first create our own simulated data. Then we will use this simulated data to build an SVM classifier. Let’s create a simulated data #Two independent variables set.seed( 1 ); x1 = rnorm( 500 , mean= 5 , sd= 3 ); mx1 = mean(x1) set.seed( 10 ); x2 = rnorm( 500 , mean= 10 , sd= 8 ); mx2 = mean(x2) # Response variable with two classes -1 and +1 y = ifelse((x2>= mx2 & x1>=mx1), 1 , - 1 ) y [x1< 2.5 ] = 1 #To add more non-linearity in the data plot(x2, x1, pch= 3 +y, col=ifelse( 1 +y, "red" , "blue" )) #Plot the data lines(c( 20 , 0 ),c( 0 , 5 ), lwd= 5 , col= "orange" ) lines(c( 30 , 0 ),c( 0 , 16 ), lwd= 5 , col= "green" ) From the plot, we can clearly see that the classes cannot be divided by...

R Programming 1

  Lab_R_1_RM Asmi Ariv 2022-10-13 R Programming In this lab we will go through some basic operations in R Simple Calculator (try the following in R): 11 + 12 20 - 30 2 * 3 10 / 5 1 + ## Error: <text>:10:0: unexpected end of input ## 8: ## 9: 1+ ## ^ Mathematical Operations (try the following in R): 11 * 9 *( 2 + 3 + 5 )/ 6 ## [1] 165 2.334 - 0.297 ## [1] 2.037 10 ^ 2 ; 10 ** 2 #Seperate different codes by semi-colon (;), use hash (#) for comments ## [1] 100 ## [1] 100 40 %% 10 ; 40 %% 9 ## [1] 0 ## [1] 4 Relational/Logical Operations (try the following in R): 4 < 5 ## [1] TRUE 2 <= 3 ## [1] TRUE 4 > 5 ## [1] FALSE 6 >= 3 ## [1] TRUE 4 == 4 ## [1] TRUE 3 != 2 ## [1] TRUE ! ( 2 == 2 ) ## [1] FALSE ( 2 == 2 ) | ( 2 == 3 ) ## [1] TRUE ( 2 == 2 ) & ( 2 == 3 ) ## [1] FALSE ( 6 >= 9 & 7 < 9 ) ## [1] FALSE ( 6 >= 9 | 7 < 9 ) ## [1] TRUE Creating and using variables (try the following in R): price = 100 ; price ## [1] 100 quantity...

Time Series Forecasting in R

  Lab_TS_1_RM Asmi Ariv 2022-10-10 Time Series Forecasting In this lab will go through time series data and how to build a machine learning model to forecast values for future periods. Kindly go through the video lectures before proceeding with this lab. We will use forecast and tseries package for this lab library (forecast) library (tseries) To begin with we will use the dataset AirPassengers from base R. It is the classic Box & Jenkins airline data. Monthly totals of international airline passengers, 1949 to 1960. The format of the data is monthly time series, in thousands. Analysing the data dim(AirPassengers) ## NULL length(AirPassengers) ## [1] 144 start(AirPassengers) ## [1] 1949 1 end(AirPassengers) ## [1] 1960 12 class(AirPassengers) ## [1] "ts" sum(is.na(AirPassengers)) ## [1] 0 AirPassengers ## Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec ## 1949 112 118 132 129 121 135 148 148 136 119 104 118 ## 1950 115 126 141 135 125 149 170 170 158 133 114 140...