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

Metaverse needs better technology, scalable infra, strong governance

Many minds have been intrigued by the idea of metaverse, and its effect is such that the social media giant like Facebook has been rebranded as Meta. Yet, there is a big question mark on the future of this technology. The enablers of metaverse such as augmented reality, mixed reality and virtual reality operating on computers, smartphones and other devices have failed to give the complete real-world like immersive experience to end users. There is a clear lack of standard virtual environment and technical specifications for implementing metaverse  –  a bottleneck in using technologies from different proprietors. Due to the business privacy and transparency concerns, interoperability of services from various providers has become a big challenge. Although, the efforts to standardize virtual reality, such as Universal Scene Description, glTF and OpenXR may help in a long run, but a lot more needs to be put in.  The technologies and devices, such as wireless he...

What is ChatGPT?

Introduction ChatGPT is a language model developed by OpenAI based on the GPT-3.5 architecture. It is designed to perform various natural language processing tasks such as language translation, text summarization, question-answering, and chatbot interactions. In this blog, we will discuss ChatGPT, its architecture, applications, and benefits. Architecture ChatGPT is based on the GPT-3.5 architecture, which is an extension of the GPT-3 architecture. The model has 175 billion parameters, making it one of the largest language models available. The architecture consists of 96 transformer blocks with a hidden size of 12,288 and 10 attention heads. The model is trained using a combination of unsupervised and supervised learning techniques. Applications ChatGPT has a wide range of applications in various fields such as healthcare, finance, customer service, and education. Some of the applications of ChatGPT are as follows: Language translation: ChatGPT can translate text from one language to ...

Exploratory Data Analysis

  Lab_D_2_RM Asmi Ariv 2022-10-14 Exploratory Data Analysis In this lab, we will go through various steps to explore a dataset using descriptive statistics, summary of data, different graphs, etc. Factor Variables (try the following in R): data = read.csv( "patient.csv" );data #Reading patient data ## Patient Gender Age Group ## 1 Dick M 20 2 ## 2 Anna F 25 1 ## 3 Sam M 30 3 ## 4 Jennie F 28 2 ## 5 Joss M 29 3 ## 6 Don M 21 2 ## 7 Annie F 26 1 ## 8 John M 32 3 ## 9 Rose F 27 2 ## 10 Jack M 31 3 data$Gender #It is a string/character variable ## [1] "M" "F" "M" "F" "M" "M" "F" "M" "F" "M" data$Gender = factor(data$Gender,levels=c( "M" , "F" ), ordered= TRUE ) #...