AP Lab Assignment 1
AP Lab Assignment 1
Strictly for internal circulation (within KIIT) and reference only. Not for outside circulation without permission
2 Credit R Programming
Protocol
2
Students should be regular and come prepared for the lab practice.
Written Quiz and Written Viva should be conducted at any point of time and
without prior notice.
Evaluation Procedure
Type Mark
Continuous Evaluation 60
End Semester Lab Examination 40
Data Types
Variables
Operators
Basic Syntax
https://www.rstudio.com/products/rstudio/download/
It is an R-specific IDE. That means that you lose the
ability to code (easily) in multiple languages, but you
do get some features especially for R.
Use it if you mainly write R code, don’t need advanced
editor features, and want a shallow learning curve or
the ability to run remotely.
Before you get started writing R code, the most important thing to know is how
to get help. There are lots of ways to do this. Firstly, if you want help on a
function or a dataset that you know the name of, type ? followed by the name of
the function. To find functions, type two question marks (??) followed by a
keyword related to the problem to search. Special characters, reserved words,
and multiword search terms need enclosing in double or single quotes.
For example:
?mean #opens the help page for the mean function
?"+" #opens the help page for addition
?"if" #opens the help page for if, used for branching code
??plotting #searches for topics containing words like "plotting"
??"regression model" #searches for topics containing phrases like this
The functions help and help.search do the same things as ? and ??, respectively,
but with these you always need to enclose your arguments in quotes. The
following commands are equivalent to the previous lot:
help("mean")
help("+")
help("if")
help.search("plotting")
help.search("regression model")
Entering Input: At the R prompt we type expressions. The <- symbol is the
assignment operator.
x <- 1
print(x)
Evaluation: When a complete expression is entered, it is evaluated and the
result of the evaluated expression is returned. The result may be auto-printed.
x <- 5 ## nothing printed
x ## auto-printing occurs
print(x) ## explicit printing
[1] 5 => The [1] shown in the output indicates that x is a vector and 5 is its first
element.
The simplest of these objects is the vector object and there are six data
types of these atomic vectors, also termed as six classes of vectors.
Data Type Example Verify Output
Logical TRUE, FALSE v <- TRUE [1] "logical"
print(class(v))
Numeric 12.3, 5, 999 v <- 23.5 [1] "numeric"
print(class(v))
Integer 2L, 34L, 0L v <- 2L [1] "integer"
print(class(v))
Complex 3 + 2i v <- 5+10i [1] “complex"
print(class(v))
Character 'a' , "good", "TRUE", '23.4' v <- “TRUE” [1] “character"
print(class(v))
Raw "Hello" is stored as 48 65 6c 6c 6f v <- charToRaw (“TRUE”) [1] “raw"
print(class(v))
School of Computer Engineering
Vector Object cont’d
16
When the vector to be created with more than one element, c() function should
be used which means to combine the elements into a vector.
# Create a vector.
apple <-c('red','green',"yellow")
print(apple)
A list is an R-object which can contain many different types of elements inside it
like vectors, functions and even another list inside it.
# Create a list. # Print the list.
list1 <-list(c(2,5,3),21.3,sin) print(list1)
Output:- When we execute the above code, it produces the following result:
[[1]]
[1] 2 5 3
[[2]]
[1] 21.3
[[3]]
function (x) .Primitive("sin")
School of Computer Engineering
Matrices Object
18
While matrices are confined to two dimensions, arrays can be of any number of
dimensions. The array function takes a dim attribute which creates the required number
of dimension. In the below example we create an array with two elements which are 3x3
matrices each.
# Create an array.
a <-array(c('green','yellow'),dim=c(3,3,2))
print(a)
Output:- When we execute the above code, it produces the following result:
,,1 ,,2
Factors are the r-objects which are created using a vector. It stores the vector along with
the distinct values of the elements in the vector as labels. The labels are always
character irrespective of whether it is numeric or character or Boolean etc. in the input
vector. They are useful in statistical modeling.
# Create a vector.
apple_colors <-c('green','green','yellow','red','red','red','green')
# Create a factor object.
factor_apple <-factor(apple_colors)
# Print the factor.
print(factor_apple)
print(nlevels(factor_apple))
Data frames are tabular data objects. Unlike a matrix in data frame each column can
contain different modes of data. The first column can be numeric while the second
column can be character and third column can be logical. It is a list of vectors of equal
length.
Data Frames are created using the data.frame() function.
# Create the data frame.
BMI <-data.frame(gender =c("Male","Male","Female"),
height =c(152,171.5,165),
weight =c(81,93,78),
age=c(42,38,26))
print(BMI)
A variable provides named storage that the programs can manipulate. A variable in R can
store an atomic vector, group of atomic vectors or a combination of many R - objects. A
valid variable name consists of letters, numbers and the dot or underline
characters. The variable name starts with a letter or the dot not followed by a number.
Variable Assignment
The variables can be assigned values using leftward, rightward and equal to operator.
# Assignment using equal operator.
var.1 = c(0,1,2,3)
# Assignment using leftward operator.
var.2<-c("learn","R")
# Assignment using rightward operator.
c(TRUE,1)->var.3
The values of the variables can be printed using print() or cat() function. The cat()
function combines multiple items into a continuous print output.
print(var.1)
cat("var.1 is ",var.1,"\n")
School of Computer Engineering
R-Variables cont’d
23
v <-c(2,5.5,6)
t <-c(8,3,4)
print(v+t)
print(v-t)
print(v*t)
print(v/t)
print(v%%t) # Give the remainder of the first vector with the second
print(v%/%t) # Give the result of division of first vector with second (quotient)
print(v^t) # The first vector raised to the exponent of second vector
v <-c(2,5.5,6) v <-c(2,TRUE,6)
t <-c(8,3,4) t <-c(8,FALSE,4)
print(v>t) print(v&t) # Element - wise Logical AND operator
print(v<t) print(v|t) # Element - wise Logical OR operator
print(v==t) print(!v)
print(v<=t) print(v&&t) # Logical AND operator
print(v>=t) print(v||t) # Logical OR operator
print(v!=t)
Thank You
End of Lab 1
1. Initialize some variables in the R workspace. Now analyze and display what are
variables are created, then delete the single variable as well as all the created
variables.
2. Initialize some variables with different types of value. Now analyze what is the type
of those variables.
3. Write an R-script to initialize your roll no., name and branch then display all the
details.
4. Write an R-script to initialize two variables, then find out the sum, multiplication,
subtraction and division of them.
5. Write an R-script to enter a 3 numbers from the keyboard, then find out sum of all
the 3 numbers.
6. Write an R-script to enter the radius of a circle, then calculate the area and
circumference of the circle.
7. Write an R-script to calculate the compound interest of the given P, T, R.
8. Write an R-script to enter two numbers from the keyboard, then swap them
without using 3rd variable.
School of Computer Engineering
Assignment
30
9. Write an R-script to enter two numbers and implement all the relational operators
on that two numbers.
10. Write an R-script to convert given paisa into its equivalent rupee and paisa as per
the following format. 550 paisa = 5 Rupee and 50 paisa.
11. Write an R-script to convert given second into its equivalent hour, minute and
second as per the following format. Example. 7560 second = 2 Hour, 27 Minute and
40 Second.
12. Write an R-script to convert a quantity in meter entered through keyboard into its
equivalent kilometer & meter as per the following format. Example - 2430 meter =
2 Km and 430 meter.
13. A cashier has currency notes of denominations 10, 50 and 100. If the amount to be
withdrawn is input through the keyboard in hundreds, write an R-script to find the
total number of currency notes of each denomination the cashier will have to give
to the withdrawer.
14. Ramesh’s basic salary is input through the keyboard. His dearness allowance is 40%
of basic salary, and house rent allowance is 20% of basic salary. Write an R-script to
calculate his gross salary.
School of Computer Engineering