Download as pdf or txt
Download as pdf or txt
You are on page 1of 3

STA 116: STATISTICAL COMPUTING CAT II

MARKING SCHEME

INSTRUCTIONS: AnswerALL questions in the spaces provided.

QUESTION ONE
 
1 5 9 13
 
 
2 6 10 14
(a) Given Matrix X  . Write an R program that performs the following;
 
3 7 11 15
 
 
4 8 12 16

(i) Generates the matrix array (X). (2 marks)

X<-array(1:16, dim=c(4,4))

##OR

X<-matrix(1:16,nrow=4,ncol=4)

##OR

x<-c(1,5,9,13,2,6,10,14,3,7,11,15,4,8,12,16)

X<-matrix(x,nrow=4,ncol=4, byrow=T)

(ii) Generates an index array for extracting elements 13, 11 and 19. (2 marks)

i<-array(c(1,3,3,4,3,4),dim=c(3,2))

(iii) Extracts the three elements in (ii) above. (1 mark)

X[i]

(b) Given that matrix Y is created by the following R code.

Y<-matrix(c(10:19,20:29),4,5,byrow=T)

Write down matrix Y. (1 mark)

1 of 3
STA 116: STATISTICAL COMPUTING CAT II
MARKING SCHEME

## [,1] [,2] [,3] [,4] [,5]

## [1,] 10 11 12 13 14

## [2,] 15 16 17 18 19

## [3,] 20 21 22 23 24

## [4,] 25 26 27 28 29

(c) Write an R code that performs the following for the above two matrices X in (a)

and Y in (b);

(i) Computes W = X −1 Y . (2 marks)

W<-solve(X)%*%Y

(ii) Computes Z = X T Y (2 marks)

Z<-t(X)%*%Y

(iii) Solves the determinant of matrix X. (1 mark)

det(X)

(d) Create a function called power with two arguments x and y which finds the

first arguments raised to the power of second argument and prints the statement

”x,raised to the power, y, is, result”. Hence call the function power where x and

y are assigned 16 and 4 respectively. (4 marks)

power <- function(x, y) {

# function to print x raised to the power y

result <- x^y

print(paste(x,"raised to the power", y, "is", result))

power(16, 4)
STA 116: STATISTICAL COMPUTING CAT II
MARKING SCHEME

QUESTION TWO

Given that a data on hair colour and eye colour for 592 students was collected. Suppose

you save the data as hec, a txt-file format on your desktop in a folder called data. The

data has two factor variables namely; hair and eye. Write an R code that performs the

following;

(a) Reads in the data set into a data frame where the first line of the file designates

the names of the variables in the data frame. (2 marks)

hec <- read.table("hec.txt",header=T, sep=",")

(b) Plots a well labelled bar plot with the title ”Barplot for Hair colour”, x-axis labelled

as ”Hair colour”, y- axis as ”Frequency” and bar colors as ”black”,”gold”,”brown”,”red”.

(3 marks)

% barplot(table(hec$hair), main="Barplot for Hair colour",

xlab="hair colour", ylab="Frequency",

col=c("black","gold","brown","red"))

You might also like