R Questions & Solutions

Vector

  1. Create a numeric variable “num_var” with the value “42.5”.
num_var <- 42.5
  1. Create a character variable “char_var” with the value “R is fun!”
char_var <- "R is fun!"
  1. Print the data type “char_var”
char_var
## [1] "R is fun!"
  1. Create a list of “student_info” with the following elements:
  1. “name”: “Mohammad Nasir Abdullah”

  2. “age”: 18

  3. “grades”: a numeric vector with values “99, 100, 89”

student_info <- list(name = "Mohammad Nasir Abdullah",
                     age = 18,
                     grades = c(99, 100,89))
  1. Create a data frame “df_students” with the following columns
  1. “Name”: “John”, “Pablo”

  2. “Age”: “22”, “30”

  3. “Grade”: “A”, “C”

df_students <- data.frame(Name = c("John", "Pablo"),
                          Age = c(22, 30),
                          Grade = c("A", "C"))
  1. Create a numeric vector “vec_num” with the values “5,10,15,20”.
vec_num <- c(5, 10, 15, 20)
  1. Extract the second and third elements from “vec_num”.
vec_num[c(2, 3)]
## [1] 10 15
  1. Create a vector “vec_seq” that contains a sequence of number from 1 to 10.
vec_seq <- seq(10)
  1. Create a vector “vec_rand” with 5 random numbers between 1 and 100.
vec_rand <- runif(n = 5, min = 1, max = 100)
vec_rand
## [1] 96.21443 73.03983 85.30087 45.60498 94.65182
  1. Create a character vector “vec_char” with the values “apple”, “banana”, “cherry”.
vec_char <- c("apple", "banana", "cherry")
  1. Use the substr() function to extract the first 3 characters from each elements of “vec_char”.
substr(vec_char, start = 1, stop = 3)
## [1] "app" "ban" "che"
  1. Create a character vector “vec_colors” with the values “red”, “blue”, “green”, “red”, “blue”.
vec_colors <- c("blue", "green", "red", "blue")
  1. Convert “vec_colors” into a factor vector “factor_colors”.
factor_colors <- as.factor(vec_colors)
  1. Print the levels of “factor_colors”.
factor_colors
## [1] blue  green red   blue 
## Levels: blue green red
  1. Given a numeric vector “vec_bonus = c(10, 20, 30, 40, 50)”, write a code snippet to:
  1. Extract all elements greater than 25.
vec_bonus <- c(10, 20, 30, 40, 50)
vec_bonus[vec_bonus > 25]
## [1] 30 40 50
  1. Calculate the mean of the extracted elements.
mean(c(vec_bonus[vec_bonus > 25]))
## [1] 40
  1. Given the following vectors:
weights <- c(55, 68, 72, 61, 58, 75, 64, 70)
names <- c("Alice", "Bob", "Charlie", "Daisy", "Eve", "Frank", "Grace", "Henry")
  1. Identify the names of individuals whose weight is greater than 65 kg.
names(weights) <- names
weights
##   Alice     Bob Charlie   Daisy     Eve   Frank   Grace   Henry 
##      55      68      72      61      58      75      64      70
weights[weights > 65]
##     Bob Charlie   Frank   Henry 
##      68      72      75      70
  1. Find the average weight of individuals weighing less than or equal to 60 kg.
mean(weights[weights <= 60])
## [1] 56.5
  1. Extract the weights of individuals whose name starts with the letters ‘A’ or ‘D’.
weights[startsWith(names, "A") | startsWith(names, "D")]
## Alice Daisy 
##    55    61
  1. Determine the number of individuals whose weight is between 60kg and 70 kg (inclusive).
length(weights[weights[weights >= 60 & weights <= 70]])
## [1] 4
  1. Given the following vector of daily temperature (in Celsius) for a week:
temperature <- c (22, 25, 19, 21, 18, 24,23)
days <- c("Mondays", "Tuesdays", "Wednesday", "Thursday", "Friday")
  1. Identify the days when the temperature was below 20°C.
temperature_below20 <- days[temperature < 20]
temperature_below20
## [1] "Wednesday" "Friday"
  1. Calculate the difference between the highest and the lowest temperatures of the week.
difftemp <- max(temperature) - min(temperature)
difftemp
## [1] 7
  1. Determine the number of days when the temperature was between 20°C and 24C (inclusive).
length(days[temperature >= 20 & temperature <= 24])
## [1] 4
  1. Given the following vector of exam scores:
scores <- c(85, 78,92, 65, 88, 70, 95, 80, 60, 90)
students <- c("Anna", "Ben", "Cara", "Dan", "Ella", "Finn", "Grace", "Hank", "Ivy", "Jack")
  1. identify the students who scored above 90.
students[scores > 90]
## [1] "Cara"  "Grace"
  1. Find the average score of students who scored below 80.
mean(scores < 80)
## [1] 0.4
  1. Extract the scores of students whose name starts with a vowel (A, E, I, O, U).
scores[grep(("^A|^E|^I|^O|^U"), students)]
## [1] 85 88 60

Matrix

QUESTION 1

  1. Create a matrix with numbers from 1 to 12, having 4 rows. Print the matrix.
matrix(1:12, nrow = 4)
##      [,1] [,2] [,3]
## [1,]    1    5    9
## [2,]    2    6   10
## [3,]    3    7   11
## [4,]    4    8   12
  1. Now, reshape the same data into a matrix with 3 columns. Print the results.
matrix(1:12, nrow = 4, ncol = 3)
##      [,1] [,2] [,3]
## [1,]    1    5    9
## [2,]    2    6   10
## [3,]    3    7   11
## [4,]    4    8   12

QUESTION 2

  1. Create a matrix with numbers from 1 to 6, having 2 rows, filled by columns. Print the matrix.
matrix(1:6, nrow = 2)
##      [,1] [,2] [,3]
## [1,]    1    3    5
## [2,]    2    4    6
  1. Create another matrix with the same data, but this time filled by rows. Print the matrix and compare with the previous one.
matrix1 <- matrix(1:6, nrow = 2)
matrix2 <- matrix(1:6, nrow = 2, byrow = T)
matrix1;matrix2
##      [,1] [,2] [,3]
## [1,]    1    3    5
## [2,]    2    4    6
##      [,1] [,2] [,3]
## [1,]    1    2    3
## [2,]    4    5    6

QUESTION 3

  1. Create a matrix with numbers from 1 to 9 having 3 rows.
matrix(1:9, nrow = 3)
##      [,1] [,2] [,3]
## [1,]    1    4    7
## [2,]    2    5    8
## [3,]    3    6    9
  1. Assign row names as “R1”, “R2” and “R3”. Assign column names as “C1”, “C2”, and “C3”.
rownames <- c("R1", "R2", "R3")
columnnames <- c("C1", "C2","C3")
  1. Print the matrix with row and column names.
matrix (1:9, nrow = 3, ncol = 3, byrow = F,
        dimnames = list(rownames,columnnames))
##    C1 C2 C3
## R1  1  4  7
## R2  2  5  8
## R3  3  6  9

QUESTION 4

  1. Consider the matrix:
mat <- matrix(1:9, nrow=3, dimnames=list(c("R1", "R2", "R3"), c("C1", "C2", "C3")))
  1. Print the element in the second row and third column.
mat[2,3]
## [1] 8
  1. Print the entire second row.
mat[2, ]
## C1 C2 C3 
##  2  5  8
  1. Print the entire first column.
mat[ , 1]
## R1 R2 R3 
##  1  2  3

QUESTION 5

  1. Create two matrices:
A <- matrix(1:4, nrow=2) 
B <- matrix(5:8, nrow=2)
  1. Perform and print the matrix addition of A and B.
A + B
##      [,1] [,2]
## [1,]    6   10
## [2,]    8   12
  1. Perform and print the matrix multiplication of A and B.
A * B
##      [,1] [,2]
## [1,]    5   21
## [2,]   12   32

QUESTION 6

  1. Create a diagonal matrix with the numbers 4, 5, and 6 on its diagonal. Print the matrix.
diag(c(4,5,6))
##      [,1] [,2] [,3]
## [1,]    4    0    0
## [2,]    0    5    0
## [3,]    0    0    6
  1. Check if the matrix from the previous step is symmetric. Print the result.
isSymmetric.matrix(matrix1)
## [1] FALSE

QUESTION 7

  1. Create two 2x2 matrices: A=[2435] B=[1324]
A <- matrix(c(2,4,3,5), nrow = 2, ncol = 2, byrow = F)
B <- matrix(c(1,3,2,4), nrow = 2, ncol = 2, byrow = F)
  1. Perform and print matrix addition for A and B.
A;B
##      [,1] [,2]
## [1,]    2    3
## [2,]    4    5
##      [,1] [,2]
## [1,]    1    2
## [2,]    3    4
  1. Perform and print matrix subtraction for A and B.
A - B
##      [,1] [,2]
## [1,]    1    1
## [2,]    1    1

QUESTION 8

  1. Using the matrices A and B from Exercise 7:
  1. Perform and print element-wise multiplication.
A * B
##      [,1] [,2]
## [1,]    2    6
## [2,]   12   20
  1. Perform and print matrix multiplication.
A %*% B
##      [,1] [,2]
## [1,]   11   16
## [2,]   19   28

QUESTION 9

  1. For the matrix A from Exercise 7:
  1. Multiply the matrix by the scalar value 3 and print the result.
A * 3
##      [,1] [,2]
## [1,]    6    9
## [2,]   12   15
  1. Divide the matrix by the scalar value 2 and print the result.
A / 2 
##      [,1] [,2]
## [1,]    1  1.5
## [2,]    2  2.5

QUESTION 10

  1. Using the matrix A from Exercise 7:
  1. Find and print the transpose of matrix A.
t(A)
##      [,1] [,2]
## [1,]    2    4
## [2,]    3    5
  1. Find and print the inverse of matrix A. (Ensure the matrix is invertible first)
det(A)
## [1] -2
solve(A)
##      [,1] [,2]
## [1,] -2.5  1.5
## [2,]  2.0 -1.0

QUESTION 11

  1. For the matrix A from Exercise 7:
  1. Extract and print the diagonal of the matrix.
diag(A)
## [1] 2 5
  1. Raise the matrix to the power of 3 and print the result.
A * 3
##      [,1] [,2]
## [1,]    6    9
## [2,]   12   15

QUESTION 12

  1. Create a matrix C
C  <- matrix(1:9, nrow = 3, ncol = 3, byrow = T)
  1. Perform matrix multiplication of A and C. Is it possible? If not, explain why.
#It is not possible because the dimension are not compatible.
  1. Extract the 2nd row and 3rd column of matrix C and print them.
C[2,3]
## [1] 6

QUESTION 13

  1. Create the following matrix: Matrix M:
M <- matrix(1:9, nrow=3,ncol=3)
M
##      [,1] [,2] [,3]
## [1,]    1    4    7
## [2,]    2    5    8
## [3,]    3    6    9
  1. Access and print the element in the 3rd row, 1st column.
M[3, 1]
## [1] 3
  1. Retrieve the entire 2nd row. What values do you get?
M[2, ]
## [1] 2 5 8
  1. Extract the entire 3rd column. What values are present?
M[ ,3]
## [1] 7 8 9

QUESTION 14

  1. Using the matrix M from Exercise 13:
  1. Access and print the elements in the 1st and 3rd rows of the 2nd column.
M[c(1,3), 2]
## [1] 4 6
  1. Extract a submatrix containing the 1st and 2nd rows of the 1st and 3rd columns.
M[c(1,2),c(1,3)]
##      [,1] [,2]
## [1,]    1    7
## [2,]    2    8
  1. Can you retrieve all elements of M that are greater than 4? If so, which elements satisfy this condition?
M[M > 4]
## [1] 5 6 7 8 9

QUESTION 15

  1. Still with matrix M:
  1. Identify and print elements that are even numbers.
M[M %% 2 == 0]
## [1] 2 4 6 8
  1. Retrieve all elements that are less than 7 and are odd numbers.
M[M < 7 & M %% 2 == 1]
## [1] 1 3 5

QUESTION 16

  1. Once again, with matrix M:
  1. Access and print the matrix excluding the 2nd row.
M[-2, ]
##      [,1] [,2] [,3]
## [1,]    1    4    7
## [2,]    3    6    9
  1. Extract the matrix without the 1st and 3rd columns.
M[ ,c(-1,-3)]
## [1] 4 5 6

QUESTION 17

  1. Imagine matrix M represents scores of 3 students in 3 subjects. Rows represent students and columns represent subjects.
  1. If the 3rd subject is “Math”, extract scores of all students in Math.
M[ ,3]
## [1] 7 8 9
  1. The second student retook the exam for the 1st subject and scored a 5. Update the matrix to reflect this score.
M[M==2] <- 5
M
##      [,1] [,2] [,3]
## [1,]    1    4    7
## [2,]    5    5    8
## [3,]    3    6    9
  1. Calculate the average score for the 1st student across all subjects.
mean(M[1, ])
## [1] 4

Array

QUESTION 1

  1. Create a 3D array names my_array with dimensions 3x4x2 using numbers from 1 to 24. Print the array.
my_array <- array(1:24, dim = c (3,4,2))
my_array
## , , 1
## 
##      [,1] [,2] [,3] [,4]
## [1,]    1    4    7   10
## [2,]    2    5    8   11
## [3,]    3    6    9   12
## 
## , , 2
## 
##      [,1] [,2] [,3] [,4]
## [1,]   13   16   19   22
## [2,]   14   17   20   23
## [3,]   15   18   21   24
  1. Access and print the element located in the 2nd row, 3rd column, and 1st layer of my_array.
my_array[2,3,1]
## [1] 8
  1. Retrieve the entire 1st layer of my_array. What values are present?
my_array[ , ,1]
##      [,1] [,2] [,3] [,4]
## [1,]    1    4    7   10
## [2,]    2    5    8   11
## [3,]    3    6    9   12

QUESTION 2

  1. Create another 3D array named another_array with dimensions 3x4x2 using numbers from 25 to 48.
another_array <- array(25:48, dim = c(3,4,2))
  1. Perform and print the result of the element wise addition of my_array and another_array
my_array + another_array
## , , 1
## 
##      [,1] [,2] [,3] [,4]
## [1,]   26   32   38   44
## [2,]   28   34   40   46
## [3,]   30   36   42   48
## 
## , , 2
## 
##      [,1] [,2] [,3] [,4]
## [1,]   50   56   62   68
## [2,]   52   58   64   70
## [3,]   54   60   66   72
  1. Multiply my_array by a scalar value of 2. Print the result.
my_array * 2
## , , 1
## 
##      [,1] [,2] [,3] [,4]
## [1,]    2    8   14   20
## [2,]    4   10   16   22
## [3,]    6   12   18   24
## 
## , , 2
## 
##      [,1] [,2] [,3] [,4]
## [1,]   26   32   38   44
## [2,]   28   34   40   46
## [3,]   30   36   42   48
  1. Execute element-wise multipication between my_array and another_array. Print the outcome.
my_array * another_array
## , , 1
## 
##      [,1] [,2] [,3] [,4]
## [1,]   25  112  217  340
## [2,]   52  145  256  385
## [3,]   81  180  297  432
## 
## , , 2
## 
##      [,1] [,2] [,3] [,4]
## [1,]  481  640  817 1012
## [2,]  532  697  880 1081
## [3,]  585  756  945 1152

QUESTION 3

  1. Using my_array from exercise 1:
  1. Calculate and print the sum of elements along the 1st dimension (rows).
apply(my_array, MARGIN = 1, sum)
## [1]  92 100 108
  1. Compute and print the mean value for each layer (3rd dimension).
apply(my_array, MARGIN = 3, mean)
## [1]  6.5 18.5
  1. Determine the maximum value for each column across all layers. Print the results.
apply(my_array, MARGIN = 3, max)
## [1] 12 24
  1. Define a function that calculates the range (difference between maximum and minimum) of a numeric vector.
range_function <- function(my_array) {
  return(max(my_array) - min(my_array))
}

column_ranges <- apply(my_array, MARGIN = 3, FUN=range_function)
print(column_ranges)
## [1] 11 11
  1. Use the apply() function to calculate the range for each column in my_array across all layers. Print the results.
range_function <- function(my_array) {
  return(max(my_array) - min(my_array))
}

column_ranges <- apply(my_array, MARGIN = 3, FUN=range_function)
print(column_ranges)
## [1] 11 11
  1. Modify the function to also return the mean of the vector. Use apply() to retrieve both the range and mean for each row in my_array across all layers. Print the outcomes.
range_function <- function(my_array) {
  return(max(my_array) - min(my_array))
}

column_ranges <- apply(my_array, MARGIN = 3, FUN = range_function)

each_mean <- apply(my_array, MARGIN = 3, FUN = mean)

print(c(column_ranges, each_mean))
## [1] 11.0 11.0  6.5 18.5

QUESTION 4

  1. Using my_array:
  1. Define custom function that multiplies a vector by a given scalar and then adds another scalar (both scalars are arguments to function the function).
scalar_function <- function(x, k, y) {return (x*k+y)}

b.Use the apply() function to apply this custom function on my_array, choosing a multiplication scalar of 0.5 and an addition scalar of 10. Print the result.

apply(my_array, MARGIN = 3, scalar_function, k =0.5, y=10)
##       [,1] [,2]
##  [1,] 10.5 16.5
##  [2,] 11.0 17.0
##  [3,] 11.5 17.5
##  [4,] 12.0 18.0
##  [5,] 12.5 18.5
##  [6,] 13.0 19.0
##  [7,] 13.5 19.5
##  [8,] 14.0 20.0
##  [9,] 14.5 20.5
## [10,] 15.0 21.0
## [11,] 15.5 21.5
## [12,] 16.0 22.0
  1. Calculate the standard deviation for each row in my_array across all columns and layers.
apply(my_array, MARGIN = c(2,3), sd)
##      [,1] [,2]
## [1,]    1    1
## [2,]    1    1
## [3,]    1    1
## [4,]    1    1