Friday Morning Exercises¶
These are exercises that we will do in the optional class on Friday morning (and possibly spill over into Monday morning) for those who want more practice with the basics of R programming. If you can do these coding challenges with little difficulty, there is no need to attend the Friday class.
Ex 1. Write a for loop over the numbers 1 to 10, and print out the square if the number is odd and the cube if the number is even. The output should look like this:
[1] 1
[1] 8
[1] 9
[1] 64
[1] 25
[1] 216
[1] 49
[1] 512
[1] 81
[1] 1000
In [ ]:
Ex 2. A Pythagoran triplet is a set of intergers (x, y, z) such that \(x^2 + y^2 = z^2\). For example, (3, 4, 5) is a Pythagorean triplet. Find all Pythogorean triplets where the value of z is less than or equql to 20, where the numbers (x, y, z) are in non-decreasing order. Your answer shouold look like this:
[1] 3 4 5
[1] 5 12 13
[1] 6 8 10
[1] 8 15 17
[1] 9 12 15
[1] 12 16 20
In [ ]:
Ex 3. Find the position in numbers where the cumulative sum first exceeds 20. The answer should be
[1] 34
In [9]:
set.seed(123)
numbers <- runif(100)
In [ ]:
Ex 4. Find the mean, standard deviation and sum of the odd numbers between 100 and 200. The answer should be:
[1] 150
[1] 29.15476
[1] 7500
In [ ]:
Ex 5. Construct the following matrix and find its inverse.
[,1] [,2] [,3] [,4]
[1,] 0 2 3 4
[2,] 5 0 7 8
[3,] 9 10 0 12
[4,] 13 14 15 0
In [20]:
6. Simulate 10 rolls of a six-sided die. Count the number of die rols less than 3. Doo not use a for or while loop. Your solution will look like this:
[1] 6 2 1 6 5 1 4 6 4 3
[2] 3
In [ ]:
7. Write a function called peek
with signature peek(m, n)
where m is a matrix and n is an integer. If n is greater than the number
of rows of m, return m. Otherwise return n random rows from m (without
repetition).
For example, if m is
[,1] [,2]
[1,] 1 11
[2,] 2 12
[3,] 3 13
[4,] 4 14
[5,] 5 15
[6,] 6 16
[7,] 7 17
[8,] 8 18
[9,] 9 19
[10,] 10 20
peek(m, 5) might be
[,1] [,2]
[1,] 10 20
[2,] 2 12
[3,] 1 11
[4,] 8 18
[5,] 5 15
In [ ]:
8. Create a matrix m that has the following values
[,1] [,2]
[1,] 1 11
[2,] 2 12
[3,] 3 13
[4,] 4 14
[5,] 5 15
[6,] 6 16
[7,] 7 17
[8,] 8 18
[9,] 9 19
[10,] 10 20
Print the row means, row sums, column means and column sums. Normalize the column values so that the column means are 0 are the column standard deviations are 1. You can do this by subtracting the column mean from each column, then dividing by the oclumn standard deviation.
In [ ]: