-
Notifications
You must be signed in to change notification settings - Fork 0
/
ch5_array.R
95 lines (31 loc) · 1.11 KB
/
ch5_array.R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
# ch5_array
# create a multidimensional matrix
# create marks for 20 students, across 4 semesters, for 4 subjects
# create the dimensions
sem=4
rows=stringi::stri_rand_strings(20,4,"[A-Za-z]")
cols=c('math','lang','sci','arts')
marks=sample(seq(1,100),sem*length(rows)*length(cols),replace=T)
length(marks)
# create the student array
# dim -> [R,C,Lines]
arrstud = array(marks,
dim=c(length(rows),length(cols),sem),
dimnames=list(rows,cols) )
print(arrstud)
# get the semester 1 details
sem1 = arrstud[,,1]
sem1
sem2 = arrstud[,,2]
sem2
# use the array to calculate and store the total and average marks of each student for every semester
# print semester-wise total
# add 'total' and 'average' to sem matrix
sem1=cbind(sem1,
total=apply(sem1,1,sum),
average=round(apply(sem1,1,mean),2))
print(sem1)
# Find the total and average of sem3 without creating a new matrix
apply(arrstud[,,3],1,sum)
apply(arrstud[,,3],1,mean)
##