vector

  1. Create a numeric variable “num_var” with the value “42.5”.
num_var <- 42.5
num_var
## [1] 42.5
  1. Create a character variable “char_var” with the value “R is fun!”.
char_var <-"R is fun!"
char_var
## [1] "R is fun!"
  1. Print the data type “char_var”.
print (char_var)
## [1] "R is fun!"
  1. Create a list “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)) 
student_info
## $name
## [1] "Mohammad Nasir Abdullah"
## 
## $age
## [1] 18
## 
## $grades
## [1]  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 <- list (name = c("John", "Pablo"),
                     age = c(22,30),
                     grade = c("A", "C"))
df_students
## $name
## [1] "John"  "Pablo"
## 
## $age
## [1] 22 30
## 
## $grade
## [1] "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 (1:10)
vec_seq
##  [1]  1  2  3  4  5  6  7  8  9 10
  1. Create a vector “vec_rand” with 5 random numbers between 1 and 100.
vec_rand <- seq (1,100 , by = 5)
vec_rand
##  [1]  1  6 11 16 21 26 31 36 41 46 51 56 61 66 71 76 81 86 91 96
  1. Create a character vector “vec_char” with the values “apple”, “banana”, “cherry”.
vec_char <- c("apple", "banana", "cherry")
vec_char
## [1] "apple"  "banana" "cherry"
  1. Use the substr() function to extract the first 3 characters from each elements of “vec_char”.
vec_char <- substr(vec_char, 1, 3)
vec_char
## [1] "app" "ban" "che"
  1. Create a character vector “vec_colors” with the values “red”, “blue”, “green”, “red”, “blue”.
vec_colors <- c("red", "blue", "green", "red", "blue")
vec_colors
## [1] "red"   "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”.
print (factor_colors)
## [1] red   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
vec_bonus <- c(10,20,30,40,50)
  1. Extract all elements greater than 25.
vec_bonus > 25
## [1] FALSE FALSE  TRUE  TRUE  TRUE
  1. Calculate the mean of the extracted elements
mean (vec_bonus)
## [1] 30
  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 65kg.
names <- (weights >65)
names
## [1] FALSE  TRUE  TRUE FALSE FALSE  TRUE FALSE  TRUE
  1. Find the average weight of individuals weighting less than or equal to 60kg.
mean (weights [weights <= 60])
## [1] 56.5
  1. Extract the weights of individuals whose names start with the letter ‘A’ or ‘D’.
weights <- names [start= "A| D"]
weights
## [1] NA
  1. Determine the number of individuals whose weight is between 60kg and 70kg (inclusive).
length(weights[weights>= 60 & weights<= 70])
## [1] 1
  1. Given the following vector of daily temperatures (in Celsius) for a week
temperatures <- c(22, 25, 19, 21, 18, 24, 23)
days <- c("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday")
  1. Identify the days when the temperature was below 20°C.
length (days[temperatures <20])
## [1] 2
  1. Calculate the difference between the highest and lowest temperatures of the week.
max(temperatures)-min(temperatures)
## [1] 7
  1. Determine the number of days when the temperature was between 20°C and 24°C (inclusive).
length (days [ temperatures >= 20 & temperatures <=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 [scores <80])
## [1] 68.25
  1. Extract the scores of students whose names start with a vowel (A, E, I, O, U).
scores[startsWith(students,"A")|startsWith(students,"E")|startsWith(students,"I")|
         startsWith(students,"O")|startsWith(students,"U")]
## [1] 85 88 60

#TAKE HOME EXERCISE

  1. Create a numeric vector containing the numbers from 10 to 20 and a character vector containing the days of the week. Display both vectors.
numeric_vector <- c(10,11,12,13,14,15,16,17,18,19,20)
character_vector <- c("Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday")
  1. Given two vectors: a <- c(1, 2, 3) and b <- c(4, 5, 6), concatenate them to form a single vector.
a <- c(1, 2, 3)
b <- c(4, 5, 6)
c(a,b)
## [1] 1 2 3 4 5 6
  1. Given the vector_temperatures <- c(15, 18, 20, 22, 19, 17, 16), extract the temperatures for the 2nd, 4th, and 6th days.
temperatures <- c(15, 18, 20, 22, 19, 17, 16)
a.mess <- temperatures
a.mess[c(2,4,6)]
## [1] 18 22 17
  1. From the same_temperatures_vector, omit the temperature of the 5th day.
a.mess[5]
## [1] 19
  1. Given the vector_prices <- c(10, 20, 30, 40, 50), calculate the new prices after a 10% discount.

{r}

  1. Create a vector that contains the numbers from 5 to 50, but only includes every 5th number (i.e. 5, 10, 15, …).
seq (5,20, by=5)
## [1]  5 10 15 20
  1. Simulate the results of rolling a 6-sided die 10 times.
rep (6, times=10)
##  [1] 6 6 6 6 6 6 6 6 6 6
  1. Given the vector_fruits <- c(“apple”, “banana”, “cherry”), extract the first three letters of each fruit.
fruits <- c("apple", "banana", "cherry")
substr (fruits, start=1 , stop=3)
## [1] "app" "ban" "che"
  1. Given the vector_ages <- c(25, 30, 35, 40, 45, 50), identify which ages are greater than 30 and less than 50.
ages <- c(25, 30, 35, 40, 45, 50)
length (ages [ages > 30 & ages < 50])
## [1] 3
  1. Given two vectors:vector1 <- c(5, 10, 15) and vector2 <- c(10, 10, 20), determine which elements of vector1 are less than or equal to the corresponding elements in vector2.
vector1 <- c(5, 10, 15)
vector2 <- c(10, 10, 20)
comparison_result <- (vector1<= vector2)
comparison_result
## [1] TRUE TRUE TRUE

matrix

#Exercise 1: Basic Matrix Creation

  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

2.Now, reshape the same data into a matrix with 3 columns. Print the result.

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

Exercise 2: Filling Order

  1. Create a matrix with numbers from 1 to 6, having 2 rows, filled by columns. Print the matrix.
matrix(1:6, nrow=2, byrow=FALSE)
##      [,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.
matrix(1:6, nrow=2, byrow=TRUE)
##      [,1] [,2] [,3]
## [1,]    1    2    3
## [2,]    4    5    6

Exercise 3: Naming Matrix Dimensions

  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,
dimnames = list(rownames, columnnames))
##    C1 C2 C3
## R1  1  4  7
## R2  2  5  8
## R3  3  6  9

Exercise 4: Accessing Matrix Elements

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

Exercise 5: Matrix Operations

  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,]    1    3
## [2,]    2    4

Exercise 6: Advanced Matrix Creation

  1. Create a diagonal matrix with the numbers 4, 5, and 6 on its diagonal. Print the matrix.
I <- c(4,5,6)
diag(I)
##      [,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(I)
## [1] FALSE

Exercise 7: Basic Matrix Operations

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

Exercise 8: Matrix Multiplication

  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,]    0    1
## [2,]    1    1

Exercise 9: Scalar Operations

  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

Exercise 10: Transposition and Inversion

  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

Exercise 11: Diagonal and Power Operations

  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,]    8   27
## [2,]   64  125

Exercise 12: Advanced Operations

  1. Create a matrix C
C<- matrix(1:9, nrow=3, ncol=3, byrow=TRUE)
print(C)
##      [,1] [,2] [,3]
## [1,]    1    2    3
## [2,]    4    5    6
## [3,]    7    8    9
  1. Perform matrix multiplication of A and C. Is it possible? If not, explain why.
#is it not possible because non-comformable arrays.
  1. Extract the second row and third column of matrix C and print them.
#C<- c[2,3]

Exercise 13: Basic Matrix Indexing

  1. Create the following matrix:

Matrix M:

M<-matrix(1:9, nrow=3,ncol=3)
  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

Exercise 14: Advanced Matrix Indexing

  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

Exercise 15: Conditional Indexing

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

Exercise 16: Negative Indexing

Once again, with matrix M:

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

Exercise 17: Practical Application

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
  1. Calculate the average score for the 1st student across all subjects.
mean(M[1,])
## [1] 4

Array

Exercise 1: Basic Array Operations

  1. Create a 3D array named my_array with dimensions 3x4x2 using numbers from 1 to 24. Print the array.
data_vector <- 1:24
dim_vector <- c(3,4,2)
my_array <- array(data_vector, dim=dim_vector)
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

Exercise 2: Array Arithmetic

  1. Create another 3D array named another_array with dimensions 3x4x2 using numbers from 25 to 48.
data_vector <- 25:48
dim_vector <- c(3,4,2)
another_array <- array(data_vector, dim=dim_vector)
another_array
## , , 1
## 
##      [,1] [,2] [,3] [,4]
## [1,]   25   28   31   34
## [2,]   26   29   32   35
## [3,]   27   30   33   36
## 
## , , 2
## 
##      [,1] [,2] [,3] [,4]
## [1,]   37   40   43   46
## [2,]   38   41   44   47
## [3,]   39   42   45   48
  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 multiplication 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

Exercise 3: Using apply() with Arrays

  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=c(2,3), max)
##      [,1] [,2]
## [1,]    3   15
## [2,]    6   18
## [3,]    9   21
## [4,]   12   24
  1. Define a function that calculates the range (difference between maximum and minimum) of a numeric vector.
range_function <- function(x){return(max(x)-min(x))}
  1. Use the apply() function to calculate the range for each column in my_array across all layers. Print the results.
apply(my_array, MARGIN=3, range_function)
## [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.
mean_range <- function(x){return (c(max(x)-min(x), mean(x)))}
apply(my_array, MARGIN=c(1,3), FUN=mean_range)
## , , 1
## 
##      [,1] [,2] [,3]
## [1,]  9.0  9.0  9.0
## [2,]  5.5  6.5  7.5
## 
## , , 2
## 
##      [,1] [,2] [,3]
## [1,]  9.0  9.0  9.0
## [2,] 17.5 18.5 19.5

Exercise 4: Advanced apply() Usage

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