Professional Documents
Culture Documents
UNIVERSITY
SCHOOL OF TECHNOLOGY
This to certify that the Practical File titled R programming Practical File submitted by Mohd
Shakir(GU17R0462) for the partial fulfillment of the requirements for the degree of bachelor of technology
(B.tech(C.S)) embodies the bonafide work done by him under the supervision.
Shagufta Parveen
Signature-
Place-
INDEX
Program Objective Remark
1. Vectors
Logical Vectors and operators
2.
3. Missing Values
4. Character vector exercises
5. Index Vector
6. Comparing vectors
7. Mode Exercises
8. Practical uses of R objects:some example
9. Factor Exercises
10. Using factor variable like a pro
11. Facing the facts about factors
12. Fighting factors with cats
13. Working with factors
14. Matrix Exercises
15. Array Exercises
16. Blind Exercises
17. Matrix Operations
18. List Exercises
19. Know your list
20. Data Frames
21. Merging Data Frames Exercises
22. Accessing Data Frame objects Exercises
23. Apply Functions to lists
Exercises based on vectors.
1. Vectors
# Creating a sequence from 5 to 13.
v <- 5:13
print(v)
# If the final element specified does not belong to the sequence then it is discarded. v
<- 3.8:11.4
print(v)
2)Logical Vectors and Operators
v <- c( 2,5.5,6) t
<- c(8, 3, 4)
print(v+t)
print(x)
round(x, 2) print(x)
#Example 1 x <-
print(nchar(x))
#Example-2
print(nchar(x)) #Example-3
lname))
#Example-4
print(vector(mode="character", length=10))
5)Index Vectors
s = c("aa", "bb", "cc", "dd", "ee") print(s[3])
#negative index
print(s[-3])
#Out-of-Range
print(s[10])
6)Comparing Vectors
#single value comparsion
x <- 9 y
<- 10
x == y
x == y
identical(x, y)
#example-2
all.equal(x, y)
mode(3.32e16)
mode(sqrt(-2i))
mode(pressure)
#Excercise 3
x <- c('1', '2', '3')
print(y)
x+1
Ex-Checking input values mysum
<- function(a, b) {
if(is.numeric(a) & is.numeric(b)) a + b
else NA
}
mysum(10, 20)
## [1] 30
mysum(10, 'a')
#Ex. 3: Subsetting
df <- data.frame(years=1991:2010, v=sample(1:10, 20000, T))
mytable[, as.character(2005:2010)]
print(mytable)
factor(numeric_var) print(attributes(numeric_var))
print(attributes(factor_numeric_var))
factor(character_var)
print(attributes(character_var))
## NULL print(attributes(factor_character_var))
11)facing the facts about factors
Exercise 1
Load the gapminder data-set from the gapminder package. Save it to an object called gp.
Check programmatically how many factors it contains and how many levels each factor has.
library(gapminder) gp
<- gapminder
Exercise 2
Notice that one continent, Antarctica, is missing from the corresponding factor – add it as the
last level of six.
c(levels(gp$continent), "Antartica")
Actually, you change your mind. There is no permanent human population on Antarctica.
Drop this (unused) level from your factor. Can you find three ways to do this, then you are an
expert gp$continent <- factor(gp$continent)
12)fighting factors with cats
Exercise 1
Load the gapminder data-set from the gapminder package, as well as forcats. Check what the
levels of the continent factor variable are and their frequency in the data.
library(gapminder) library(forcats)
Exercise 2
Notice that one continent, Antarctica, is missing – add it as the last level of six.
Actually, you change your mind. There is no permanent human population on Antarctica.
Drop this (unused) level from your factor.
fct_count(gp$continent)
Calculate the number of occurrences per level for the rincome column.
library(forcats)
fct_count(gss_cat$rincome)
Exercise 2
Re-order the levels of rincome by first occurrence of the level in the data-set.
fct_count(fct_inorder(gss_cat$rincome))
Exercise 3
Re-order the levels of rincome by frequency in the data-set.
fct_count(fct_infreq(gss_cat$rincome))
Exercise based on Arrays and Matrices 14)Matrix Excercises
R program to create a blank matrix.
m = matrix(, nrow = 10, ncol = 5)
print("Empty matrix of 10 rows and 5 columns:") print(m)
R program to create a matrix taking a given vector of numbers as input and define
the column and row names. Display the matrix
row_names = c("row1", "row2", "row3", "row4") col_names
print("Original Matrix:")
print(M)
15)Array Excercises
R program to convert a given matrix to a 1 dimensional array
m=matrix(1:12,3,4)
print("Original matrix:")
print(m) a = as.vector(m)
print("1 dimensional array:")
print(a)
R program to create an array of two 3x3 matrices each with 3 rows and 3
columns from two given two vectors.
v1 = c(1,3,4,5) v2 = c(10,11,12,13,14,15)
array:") print(result)
Exercise 2
Repeat exercise 1, binding vectors row-wise instead of column-wise while avoiding any row names.
a <- 1:5; b <- 1:5 m <- rbind(a, b,
deparse.level=0) is.matrix(m)
mode(m)
a <- 1:5; b <- c('1', '2', '3', '4', '5')
m
is.matrix(m)
mode(m)
rbind(a, b, deparse.level=0)
is.matrix(m)
mode(m)
Exercise 3
Bind the following matrices column-wise. First, without using R, write down whether binding
the matrices is actually possible; then the resulting matrix and its mode (e.g., character,
numeric etc.).
a <- matrix(1:12, ncol=4) ; b <- matrix(21:35, ncol=5)
mode(m)
m <- cbind(a, b)
mode(m)
17)Matrix Operation
Matrix Addition & Subtraction
A <- matrix(c(2,3,-2,1,2,2),3,2)
B <- matrix(c(1,4,-2,1,2,1),3,2)
C <- A + B
Print(c)
R program to list containing a vector, a matrix and a list and give names to the
elements in the list
list_data <- list(c("Red","Green","Black"), matrix(c(1,3,5,7,9,11), nrow = 2),
print(list_data)
R program to create a list containing a vector, a matrix and a list and give names
to the elements in the list. Access the first and second element of the list.
x
Exercise 2
Add a third vector of length 1 to x, z = 3.
x["c"] <- 3 x
Exercise 3
Turn your list into a named vector called y with only one line of code.
y <- unlist(x)
y
20)Data Frames.
# Create the data frame. emp.data
<- data.frame(
c("Rick","Dan","Michelle","Ryan","Gary"), salary =
c(623.3,515.2,611.0,729.0,843.25),
start_date = as.Date(c("2012-01-01","2013-09-23","2014-11-15","2014-05-11",
"2015-03-27")),
stringsAsFactors = FALSE
Exercise 1
Create the dataframes to merge: buildings <-
data.frame(location=c(1, 2, 3), name=c("building1",
"building2", "building3"))
The dataframes, buildings and data have a common key variable called, “location”.
Use the merge() function to merge the two dataframes by “location”, into a new
dataframe, “buildingStats”.
by="location")
Exercise 2
Give the dataframes different key variable names:
buildings <- data.frame(location=c(1, 2, 3), name=c("building1",
"building2", "building3"))
data <- data.frame(survey=c(1,1,1,2,2,2),
LocationID=c(1,2,3,2,3,1), efficiency=c(51,64,70,71,80,58))’
# Give the dataframes different key variable names: buildings <- data.frame(location=c(1, 2, 3),
LocationID=c(1,2,3,2,3,1), efficiency=c(51,64,70,71,80,58))
by.x="location",
by.y="LocationID")
Exercise 3 Inner
Join:
The R merge() function automatically joins the frames by common variable
names. In that case, demonstrate how you would perform the merge in Exercise 1
without specifying the key variable.
# Solution
buildingStats <- merge(buildings, data)
22)Accessing data frame objects exercises
Exercise 1 attach() – Attach a set of R Objects to
Search Path
Required Dataframe:
buildingSurvey <- data.frame(name=c("bldg1", "bldg2", "bldg3",
"bldg4", "bldg5", "bldg6"),
survey=c(1,1,1,2,2,2),
location=c(1,2,3,2,3,1), floors=c(5,
10, 10, 11, 8, 12),
efficiency=c(51,64,70,71,80,58))
attach(buildingSurvey) summary(floors)
Exercise 2
Using the “summary()” function, find the median “efficiency” value of
“buildingSurvey“, using objects in the R environment search path.
summary(efficiency)
Exercise 3
Once attached, in order to change the dataframe variable, use the assignment
lapply(list1, length)
Exercise 2
lapply(list1, sum)
Exercise 3
Exercise 4
class)