Professional Documents
Culture Documents
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
# 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
,,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
[,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