You are on page 1of 10

AI&ML

Week 4 Exercises
DrAPS
Week 4 Exercises
• Implement R script to perform following operations:
a) various operations on vectors
b) Finding the sum and average of given numbers using arrays.
c) To display elements of list in reverse order.
d) Finding the minimum and maximum elements in the array
Week 4 Exercises
a) various operations on vectors
> a = c(1, 3, 5, 7)
> b = c(1, 2, 4, 8)
>5*a Output: [1] 5 15 25 35

>a+b Output: [1] 2 5 9 15

>a-b Output: [1] 0 1 1 -1

>a*b Output: [1] 1 6 20 56

>a/b Output: [1] 1.000 1.500 1.250 0.875

# Recycling Rule
> u = c(10, 20, 30)
> v = c(1, 2, 3, 4, 5, 6, 7, 8, 9)
>u+v Output: [1] 11 22 33 14 25 36 17 28 39
Week 4 Exercises
Arrays
• In R, arrays are the data objects which allow us to store data in more
than two dimensions.
• In R, an array is created with the help of the array() function.
• This array() function takes a vector as an input and to create an array
it uses vectors values in the dim parameter.
• if we will create an array of dimension (2, 3, 4) then it will create 4 rectangular
matrices of 2 row and 3 columns.
• Syntax: array_name <-
array(data, dim= (row_size, column_size, matrices, dim_names))
Week 4 Exercises
Output

#Creating two vectors of different lengths ,,1


[,1] [,2] [,3]
vec1 <-c(1,3,5) [1,] 1 10 13
[2,] 3 11 14
vec2 <-c(10,11,12,13,14,15) [3,] 5 12 15

,,2
#Taking these vectors as input to the array [,1] [,2] [,3]
[1,] 1 10 13
res <- array(c(vec1,vec2),dim=c(3,3,2)) [2,] 3 11 14
[3,] 5 12 15
print(res)
Week 4 Exercises
> rnames <- c("r1","r2","r3") Output
, , m1
> cnames <- c("c1","c2","c3")
> mnames <- c("m1","m2","m3") c1 c2 c3
r1 1 4 7
> named_array <- array(c(1:27),dim=c(3,3,3),dimnames= r2 2 5 8
r3 3 6 9
list(rnames,cnames,mnames))
> named_array , , m2

c1 c2 c3
r1 10 13 16
r2 11 14 17
r3 12 15 18

, , m3

c1 c2 c3
r1 19 22 25
r2 20 23 26
r3 21 24 27
Week 4 Exercises
b) Finding the sum and average of given numbers using arrays Output
Sum ,,1

> test_arr1 <- array(c(1:8),dim=c(2,2,2)) [,1] [,2]


[1,] 10 14
> test_arr2 <- array(c(9:16),dim=c(2,2,2)) [2,] 12 16
> arr_add <- test_arr1+test_arr2
,,2
> arr_add
[,1] [,2]
[1,] 18 22
[2,] 20 24
Week 4 Exercises
Average Output
> test_arr1 <- array(c(1:8),dim=c(2,2,2)) ,,1

> test_arr2 <- array(c(9:16),dim=c(2,2,2)) [,1] [,2]


[1,] 5 7
> arr_add <- (test_arr1+test_arr2)/2 [2,] 6 8
> arr_add
,,2

[,1] [,2]
[1,] 9 11
[2,] 10 12
Week 4 Exercises
c) To display elements of list in reverse order Output: [1] 1 2 3 4 5
# Create a vector
vec <- 1:5
vec

# Apply rev() function to vector Output: [1] 5 4 3 2 1


vec_rev <- rev(vec)
vec_rev
Week 4 Exercises
d) Finding the minimum and maximum elements in the array

>x <- array(c(1:12), dim=c(3,2,2))


>x
>result_max <- max(x)
>cat("Maximum value is :", result_max)
>result_min <- min(x)
>cat("Maximum value is :", result_min)

You might also like