Q1

Create a list using R with the following values g1=1:10, g2=“R Programming”, g3= “HTML”. Then, count the number of objects in the list. After that, get the length of the first two vectors of the given list.

Q1list <- list(g1 = 1:10, g2 = "R Programming", g3 = "HTML")
length(Q1list)
## [1] 3
length(Q1list[[1]])
## [1] 10
length(Q1list[[2]])
## [1] 1

Q2

Find all elements of a list2 that are not given in list1 using R. Given list1 consists of (“x”, “y”, “z”) and list2 consists of “x”, “y”, “z”, “X”, “Y”, “Z”. (You can use the setdiff())

list1 <- list("x", "y", "z")
list2 <- list("x", "y", "z", "X", "Y", "Z")

diff_list2 <- setdiff(list2, list1) #the list in check must be first
print(diff_list2)
## [[1]]
## [1] "X"
## 
## [[2]]
## [1] "Y"
## 
## [[3]]
## [1] "Z"

Q3

Create a list using the following values (“G022”, “G003”, “G013”, “G007”, “G012” and then list down the number of items in the list. Then, display the second element in the list. After that, add a new item “G018”to the list and then display the list in ascending order.

Q3list <- list("G022", "G003", "G013", "G007", "G012")
#number of items in list
length(Q3list)
## [1] 5
#display 2nd element
Q3list[[2]]
## [1] "G003"
#add new item to the list
Q3list[[6]] <- "G018" #can also use Q3list <- append(Q3list,"G018") or c(Q3list,"G018")
Q3list
## [[1]]
## [1] "G022"
## 
## [[2]]
## [1] "G003"
## 
## [[3]]
## [1] "G013"
## 
## [[4]]
## [1] "G007"
## 
## [[5]]
## [1] "G012"
## 
## [[6]]
## [1] "G018"
#display list in ascending order
sortedQ3 <- sort(unlist(Q3list)) #for sorting must unlist the list
sortedQ3
## [1] "G003" "G007" "G012" "G013" "G018" "G022"

Q4

Create four vectors a, b, c, and d with 3 integers. Combine all the vectors to become a 4x3 matrix. Add a vector with sequence of number from 1 to 4 to the matrix by row.

a <- 5:7
b <- 8:10
c <- 11:13
d <- 14:16
Q4matrix <- rbind(a,b,c,d) # answer during class discussion
# can also use:
# Q4matrix <- matrix(c(a,b,c,d),4,3)
Q4matrix
##   [,1] [,2] [,3]
## a    5    6    7
## b    8    9   10
## c   11   12   13
## d   14   15   16
e <- 1:4
# adding vector by row, since different dimension, must transpose the matrix first
newQ4m <- t(Q4matrix) # transpose the matrix
newQ4m <- rbind(newQ4m, e) # adding vector by row
newQ4m <- t(newQ4m) # transpose the matrix back
newQ4m
##            e
## a  5  6  7 1
## b  8  9 10 2
## c 11 12 13 3
## d 14 15 16 4

Q5

A and B is a 3x4 matrix. Create an R Script to multiply matrix A and B to get the 3x3 dimension.

R script content:

#build matrix A & B
A <- matrix(1:12, nrow=3, ncol=4)
A
##      [,1] [,2] [,3] [,4]
## [1,]    1    4    7   10
## [2,]    2    5    8   11
## [3,]    3    6    9   12
B <- matrix(1:12, nrow=3, ncol=4)
B
##      [,1] [,2] [,3] [,4]
## [1,]    1    4    7   10
## [2,]    2    5    8   11
## [3,]    3    6    9   12
#Multiply matrices
MultM <- A %*% t(B)
MultM
##      [,1] [,2] [,3]
## [1,]  166  188  210
## [2,]  188  214  240
## [3,]  210  240  270

Q6

Create a matrix with 10 rows and 2 columns, extract a sub-matrix from original matrix which includes the last 5 rows.

#build matrix
C <- matrix(1:20, nrow=10, ncol=2)
C
##       [,1] [,2]
##  [1,]    1   11
##  [2,]    2   12
##  [3,]    3   13
##  [4,]    4   14
##  [5,]    5   15
##  [6,]    6   16
##  [7,]    7   17
##  [8,]    8   18
##  [9,]    9   19
## [10,]   10   20
#extract submatrix
subC <- C[(nrow(C)-4):nrow(C),] # or directly C[6:10,]
subC
##      [,1] [,2]
## [1,]    6   16
## [2,]    7   17
## [3,]    8   18
## [4,]    9   19
## [5,]   10   20
#another method
tail(C,5)
##       [,1] [,2]
##  [6,]    6   16
##  [7,]    7   17
##  [8,]    8   18
##  [9,]    9   19
## [10,]   10   20

Q7

A square matrix A is said to be invertible if there exists a matrix B such that AB = BA = I. Generate a 2x2 matrix A as below.
the matrix
Then, compute B.

#generate matrix
A <- matrix(c(2, 2, 4, 2), nrow = 2, byrow = TRUE)
A
##      [,1] [,2]
## [1,]    2    2
## [2,]    4    2
#compute B
B <- solve(A) # R function to find inverse matrix
B
##      [,1] [,2]
## [1,] -0.5  0.5
## [2,]  1.0 -0.5

Q8

With regards to the mtcars dataset:
- retrieve the number of columns

ncol(mtcars)
## [1] 11
nrow(mtcars)
## [1] 32
print(mtcars[3,5])
## [1] 3.85
print(mtcars["Datsun 710", "drat"])
## [1] 3.85
print(mtcars["Volvo 142E",])
##             mpg cyl disp  hp drat   wt qsec vs am gear carb
## Volvo 142E 21.4   4  121 109 4.11 2.78 18.6  1  1    4    2
print(mtcars[,"mpg"])
##  [1] 21.0 21.0 22.8 21.4 18.7 18.1 14.3 24.4 22.8 19.2 17.8 16.4 17.3 15.2 10.4
## [16] 10.4 14.7 32.4 30.4 33.9 21.5 15.5 15.2 13.3 19.2 27.3 26.0 30.4 15.8 19.7
## [31] 15.0 21.4
print(mtcars[,c("hp","qsec")])
##                      hp  qsec
## Mazda RX4           110 16.46
## Mazda RX4 Wag       110 17.02
## Datsun 710           93 18.61
## Hornet 4 Drive      110 19.44
## Hornet Sportabout   175 17.02
## Valiant             105 20.22
## Duster 360          245 15.84
## Merc 240D            62 20.00
## Merc 230             95 22.90
## Merc 280            123 18.30
## Merc 280C           123 18.90
## Merc 450SE          180 17.40
## Merc 450SL          180 17.60
## Merc 450SLC         180 18.00
## Cadillac Fleetwood  205 17.98
## Lincoln Continental 215 17.82
## Chrysler Imperial   230 17.42
## Fiat 128             66 19.47
## Honda Civic          52 18.52
## Toyota Corolla       65 19.90
## Toyota Corona        97 20.01
## Dodge Challenger    150 16.87
## AMC Javelin         150 17.30
## Camaro Z28          245 15.41
## Pontiac Firebird    175 17.05
## Fiat X1-9            66 18.90
## Porsche 914-2        91 16.70
## Lotus Europa        113 16.90
## Ford Pantera L      264 14.50
## Ferrari Dino        175 15.50
## Maserati Bora       335 14.60
## Volvo 142E          109 18.60
#another method
data <- subset(mtcars,select = c("hp","qsec"))
data
##                      hp  qsec
## Mazda RX4           110 16.46
## Mazda RX4 Wag       110 17.02
## Datsun 710           93 18.61
## Hornet 4 Drive      110 19.44
## Hornet Sportabout   175 17.02
## Valiant             105 20.22
## Duster 360          245 15.84
## Merc 240D            62 20.00
## Merc 230             95 22.90
## Merc 280            123 18.30
## Merc 280C           123 18.90
## Merc 450SE          180 17.40
## Merc 450SL          180 17.60
## Merc 450SLC         180 18.00
## Cadillac Fleetwood  205 17.98
## Lincoln Continental 215 17.82
## Chrysler Imperial   230 17.42
## Fiat 128             66 19.47
## Honda Civic          52 18.52
## Toyota Corolla       65 19.90
## Toyota Corona        97 20.01
## Dodge Challenger    150 16.87
## AMC Javelin         150 17.30
## Camaro Z28          245 15.41
## Pontiac Firebird    175 17.05
## Fiat X1-9            66 18.90
## Porsche 914-2        91 16.70
## Lotus Europa        113 16.90
## Ford Pantera L      264 14.50
## Ferrari Dino        175 15.50
## Maserati Bora       335 14.60
## Volvo 142E          109 18.60

Q9

Create a DataFrame using the following data. SK020 is the ProductCode, Enfagrow A+ is the ProductName and 36.79 is the Price. the dataset

ProductData <- data.frame(
  ProductCode = c("SK020","SK042","SK013","SK066","SK079"),
  ProductName = c("Enfagrow A+","Ayamas Nuget Crispy","100 Plus","Ali Cafe","Dettol Natural"),
  Price = c(36.79, 9.99, 6.49, 8.99, 4.99)
)

Then, solve the following statements
▪ Display the information above in a table.

print(ProductData)
##   ProductCode         ProductName Price
## 1       SK020         Enfagrow A+ 36.79
## 2       SK042 Ayamas Nuget Crispy  9.99
## 3       SK013            100 Plus  6.49
## 4       SK066            Ali Cafe  8.99
## 5       SK079      Dettol Natural  4.99

▪ Display the information above in a table sort by product name in ascending order.

sortedPD <- ProductData[order(ProductData$ProductName),]
print(sortedPD)
##   ProductCode         ProductName Price
## 3       SK013            100 Plus  6.49
## 4       SK066            Ali Cafe  8.99
## 2       SK042 Ayamas Nuget Crispy  9.99
## 5       SK079      Dettol Natural  4.99
## 1       SK020         Enfagrow A+ 36.79

▪ Add a new product SK023, Johnson PH, 5.99 to the data frame and display the information in a table sort by product name in ascending order.

ProductData <- rbind(ProductData, data.frame(ProductCode = "SK023", ProductName = "Johnson PH", Price = 5.99))
sortedPD <- ProductData[order(ProductData$ProductName),]
print(sortedPD)
##   ProductCode         ProductName Price
## 3       SK013            100 Plus  6.49
## 4       SK066            Ali Cafe  8.99
## 2       SK042 Ayamas Nuget Crispy  9.99
## 5       SK079      Dettol Natural  4.99
## 1       SK020         Enfagrow A+ 36.79
## 6       SK023          Johnson PH  5.99

▪ Display all rows where product price more than 8.00.

ProductData[with(ProductData, Price > 8.00),]
##   ProductCode         ProductName Price
## 1       SK020         Enfagrow A+ 36.79
## 2       SK042 Ayamas Nuget Crispy  9.99
## 4       SK066            Ali Cafe  8.99
#another method
subset(ProductData, Price > 8.00)
##   ProductCode         ProductName Price
## 1       SK020         Enfagrow A+ 36.79
## 2       SK042 Ayamas Nuget Crispy  9.99
## 4       SK066            Ali Cafe  8.99

▪ Display the product with maximum price and minimum price.

ProductData[c(which.max(ProductData$Price),which.min(ProductData$Price)),]
##   ProductCode    ProductName Price
## 1       SK020    Enfagrow A+ 36.79
## 5       SK079 Dettol Natural  4.99
#another method
ProductData[ProductData$Price == max(ProductData$Price),]
##   ProductCode ProductName Price
## 1       SK020 Enfagrow A+ 36.79
ProductData[ProductData$Price == min(ProductData$Price),]
##   ProductCode    ProductName Price
## 5       SK079 Dettol Natural  4.99

▪ Count the number of items where the product name begins with “A”

sum(grepl("^A", ProductData$ProductName))
## [1] 2
#another method
ProductData[startsWith(ProductData$ProductName,"A"),]
##   ProductCode         ProductName Price
## 2       SK042 Ayamas Nuget Crispy  9.99
## 4       SK066            Ali Cafe  8.99