STA1031 Assignment 3
STA1031 Assignment 3
STA1031 Assignment 3
2) Create an R function to print only the odd numbers of a given vector, using the following
instructions.
● The function name should be “odd_num”.
● Allow to include a vector called “x” as the user input.
● Print only the odd numbers in the above vector, as the output of the function.
● Obtain the count of odd numbers for the vector 2,6,4,8,5,3,1,9,7
3) Create an R function that prints all possible distinct two-item combinations from two user-
defined vectors, omitting combinations that have the same item twice (for example, (2,2)
will be omitted). Each combination should have one value from one vector and another
from another vector.
• Name the function as “combinations”.
• Obtain all possible distinct two-item combinations for the two vectors a = 1,2,3,4,5
and b = 2,3,4,5
4) Create an R function to count the number of elements in a matrix that are equal to zero and
not equal to zero. To develop the function, use the following instructions.
● The function name should be “get_counts”.
● Allow to include a matrix called 𝑀 as the user input. (Here the matrix 𝑀 can be any
numerical matrix and it can have any dimensions).
● Obtain the zero counts and non-zero counts for the 3×3 matrix with elements
0,1,2,0,5,0, -1, 2, -3
● The output of your function should be displayed as follows:
“There are 3 zeros and 6 non zeros.”
5) Create a function in R which takes 2 arguments x and n, where x is a single number and n
is a strictly positive integer. The function should return the value of,
𝑥 𝑥2 𝑥3 𝑥4 𝑥𝑛
1+ + + + +…+
1 2 3 4 𝑛
Your move
Rock Paper Scissors
Rock Tie You win You lose
Computers’ Paper You lose Tie You win
move
Scissors You win You lose Tie
• Test your program four times using different moves and submit all four of your test
results.
7) Zeller's congruence is an algorithm devised by Christian Zeller in the 19th century to
calculate the day of the week for any given date. The formula:
𝑦 𝑙
𝐹 = ([2.6𝑚 − 0.2] + 𝑘 + 𝑦 + [ ] + [ ] − 2𝑙) mod7
4 4
For example, the date 21/07/1999 has m=5, k=21, l=19, y=99; whilst the date 21/2/2009
has m=12, k=21, l=20, y=09.
Note that 𝐹 is the day of the week (Monday = 1, Tuesday = 2, …, Sunday = 0).
• Build a function in R named “weekday” which returns the day of the week when
given the numerical inputs of the day, month and year.
• Using the “weekday” function, obtain the day of 17th February 2023.
Hints:
i. The integer part of a number can be obtained by using the R command floor().
ii. When month is either January or February, year should be reduced by 1.
iii. The values of 𝑦 and 𝑙 can be obtained by using modulo and integer quotient.