We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 12
18. Write a program to illustrate Compare and Matrices and Compare Vectors
Compare two matrices
a <- matrix(1:16, ncol=2)
b <- matrix(1:16, ncol=4, dimnames=list (1:4, letters[1:4]))
d <- matrix(1:16, ncol=4)
a==b # Error in a == b : non-conformable arrays
identical(a, b) # FALSE
all.equal(a, b) # why? different dims and different dimnames
all(d == b) —# TRUE but
identical (d, b) # FALSE
all.equal(d, b) 4 why? different dimnames# An one line way of solving it.
matequal <- function(x, y) G& all(x ==
is.matrix(x) && is.matrix(y) && dim(x) == dim(y) && all(x =
Matequal(a, b) # FALSE
matequal(d, b) # TRUE
Compare two Vectors
A <- ("a
BA
Cf <- c(Mam, mem, mom, mem)
"BM, ncn,
>A==8B
(1] TRUE TRUE TRUE TRUE
This is good situation to go forward
c
[1] TRUE FALSE TRUE FALSE
19. Write a program to illustrate Logical & and Logical | operators in R.
> x <- ¢(1:10)
(x<5) ]
> x[ (x>8)
Output:
(1J"- 2 2534910
> x<-c(1:15)
> x[x>=10]
Output:
{1] 10 11 12 13 14 15Output:
20. Write a Program to illustrate Functions in Quick sort implementation in R
> quickSort <- function (vect) {
# arg:
# vect: Numeric vector
# Stop if vector has length of 1
af (length(vect) <= 1) {
return (vect)
,
# Pick an element from the vectorelement <- vect{1)
Partition <- vect[-1)
# Reorder vector so that integers 1
# come before, and all integers greater come after.
than element
vl <- partition [partition < element]
v2 <- partition[partition >= element]
# Recursively apply steps to smaller vectors.
vl <- quickSort (v1)
v2 <- quickSort (v2)
return(c(v1, element, v2))
}
> quickSort(c(4, 65, 2, -31, 0, 99, 83, 782, 1))
(1) -31 o 1 2 4 65 83 99 782
21. Write a program to illustrate Function inside function in R
A function is a set of statements organized together to perform
a specific task. R has a large number of in-built functions and
the user can create their own functions.
In R, a function is an object so the R interpreter is able to
pass control to the function, along with arguments that may be
necessary for the function to accomplish the actions.The function in turn performs its task and returns control to
the interpreter as well as any result which may be stored in
other objects.
Function Definition
An R function is created by using the keyword function. The
basic syntax of an R function definition is as follows -
eee ee <- function(arg 1, arg_2, ..-)
Function body
+
Function Components
The different parts of a function are -
* Function Name - This is the actual name of the function. It
is stored in R environment as an object with this name.
* Arguments - An argument is a placeholder. When a function
is invoked, you pass a value to the argument. Arguments are
optional; that is, a function may contain no arguments.
Also arguments can have default values.
* Function Body - The function body contains a collection of
statements that defines what the function does.
* Return Value - The return value of a function is the last
expression in the function body to be evaluated.
R has many in-built functions which can be directly called in
the program without defining them first. We can also create and
use our own functions referred as user defined functions.
Built-in Function
Simple examples of in-built functions are seq(), mean(), max(),
sum(x) and paste(...) etc. They are directly called by user
written programs. You can refer most widely used R functions.
# Create a sequence of numbers from 32 to 44.
print (seq(32,44))
# Find mean of numbers from 25 to 82.
print (mean (25:82) )
# Find sum of numbers frm 41 to 68.Print (sum(41:68))
When we execute the above code, it produces the following result
(1] 32 33 34 35 36 37 38 39 40 41 42 43 44
(1] 53.5
[1] 1526
User-defined Function
We can create user-defined functions in R. They are specific to
what a user wants and once created they can be used like the
built-in functions. Below is an example of how a function 18
created and used.
# Create a function to print squares of numbers in sequence.
new.function <- function(a) {
for(i in l:a) {
b <- i*2
print (b)
}
Calling a Function
# Create a function to print squares of numbers in sequence.
new.function <- function(a) {
for(i in 1l:a) {
b <- i*2
print (b)
}
# Call the function new.function supplying 6 as an argument.
new. function (6)
When we execute the above code, it produces the following result
(2) 1
a) 4
(19
[1] 16
[1] 25
[1] 36
Calling a Function without an Argumentte a function without an argument.
new.function <- function() {
for(i in 1:5) {
print (i*2)
}
y
# Call the function without supplying an argument.
new. function ()
When we execute the above code, it produces the following result
(2) 1
{11 4
{11 9
{1] 16
[1] 25
Calling a Function with Argument Values (by position and
by name)
The arguments to a function call can be supplied in the same
sequence as defined in the function or they can be supplied in a
different sequence but assigned to the names of the arguments.
# Create a function with arguments.
new. function <- function(a,b,c) {
result <-a*btc
print (result)
)
# Call the function by position of arguments.
new. function (5, 3, 11)
# Call the function by names of the arguments.
new. function(a = 11, b = 5, ¢ = 3)
When we execute the above code, it produces the following result
(1] 26
[1] 58
Calling a Function with Default Argument
We can define the value of the arguments in the function
definition and call the function without supplying any argument
to get the default result. But we can also call such functionsby supplying new values of the argument and get non default
result.
# Create a function wi
new. function <- function
result <- a * b
print (
)
rguments.
3, b = 6)
# call the function without
function without giving any argument.
new. function () 2 { an
4 Call the function with giving new values of the argument.
new. function (9, 5)
When we execute the above code, it produces the following result
(1) 18
(1) 45
22. Write a program to illustrate to create graphs and usage of plot () function in R
# Define the cars vector with 5 values
cars <- c(1, 3, 6, 4, 9)
# Graph the cars vector with all defaults
plot (cars)
Let's add a title, a line to connect the points, and some color:
# Define the cars vector with 5 values
cars <- c(1, 3, 6, 4, 9)
# Graph cars using blue points overlayed by a line
plot(cars, type="0", col="blue")# Create a title with a red, bold/italic font
title(main="Autos", col.main="red", font.main=4)
Now let's add a red line for trucks and specify the y-axis range
directly so it will be large enough to fit the truck data:
# Define 2 vectors
cars <- c(1, 3, 6, 4, 9)
trucks <- (2, 5, 4, 5, 12)
# Graph cars using a y axis that ranges from 0 to 12
plot(cars, type="o", col="blue", ylim=c(0,12))
# Graph trucks with red dashed line and square points
lines(trucks, type="0", pch=22, lty=2, col="red")
# Create a title with a red, bold/italic font
title (main="Autos", col.main="red", font.main=4)
Program
Next let's change the axes labels to match our data and add a legend.
We'll also compute the y-axis values using the max function so any
changes to our data will be automatically reflected in our graph.
# Define 2 vectors
ears <- c(1, 3, 6, 4, 9)
trucks <- c(2, 5, 4, 5, 12)
# Calculate range from 0 to max value of cars and trucks
g_zange <- range(0, cars, trucks)
# Graph autos using y axis that ranges from 0 to max
# value in cars or trucks vector. Turn off axes and
# annotations (axis labels) so we can specify them ourself
plot(cars, type="0", col="blue", ylim=g_range,
axes=FALSE, ann=FALSE)
# Make x axis using Mon-Fri labels
axis(1, at=1:5, lab=c("Mon","Tue","Wed","Thu" , "Fr.
»)
# Make y axis with horizontal labels that display ticks at
;_range[2] is equivalent to c(0,4,8,12).
# every 4 marks. 4*0:
axis(2, las=1, at=4*0:g_range[2])
# Create box around plotbox ()
# Graph trucks with red dashed line and square points
lines (trucks, type="0", pch=22, lty=2, col="red")
# Create a title with a red, bold/italic font
title (main="Autos", col.main="red", font.main=4)
# Label the x and y axes with dark green text
title(xlab="Days", col.lab=rgb(0,0.5,0))
title(ylab="Total", col.lab=rgb(0,0.5,0))
# Create a legend at (1, g_range[2]) that is slightly smaller
# (cex) and uses the same line colors and points used by
# the actual plots
legend(1, g_range[2], ¢("cars","trucks"), cex=0.8,
col=c("blue","red"), pch=21:22, lty=1:2);
23. Write a program to illustrate Customizing and Saving to Graphs in R.
# Pie Chart with Percentages
slices <- c(10, 12, 4, 16, 8)
lbls <- c("US", "UK", "Australia", "Germany", "France")
pet <- round(slices/sum(slices) *100)
lbls <- paste(lbls, pct) # add percents to labels
lbls <- paste(1bls,"8",sep="") # ad % to labels
pie(slices, labels = lbls, col=rainbow(length(lbls)),
main="Pie Chart of Countries")24. Write a program to illustrate some built in Mathematical Functions
Help(function name)
log (x)
logb ()
1og10()
log2()
exp()expml ()
loglp()
sqrt ()
cos ()
sin()
tan()
acos()
asin()
atan()
atan2()