Lab_R_2_RM
Asmi Ariv
2022-10-14
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] 10For 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 printingConditional 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] 11if(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 elseExercise: 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] 9Exercise: 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] 7am$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] 12save(f1, file = "f1.R") #To save the function in your working directory
load("f1.R") #To load the function in your R sessionExercise: 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 connectionGraphics (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 datapointsplot(x, y, type = "l") #plots the line joining datapointsplot(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 plotExercise: 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
## 1bmp("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] TRUEdim(iris) #To check the dimension; it has 150 records and 5 variables## [1] 150 5names(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 164You can use datasets provided in MASS package and Base R for your practice in this section as well as in the later sections.
Comments
Post a Comment