辅导案例-STATS 782

  • June 12, 2020

STATS 782 THE UNIVERSITY OF AUCKLAND SEMESTER 2, 2018 Campus: City STATISTICS Statistical Computing (Time allowed: TWO Hours) INSTRUCTIONS • This examination is in two parts, Part A and Part B. • Attempt ALL questions in Part A. • Attempt ALL questions in Part B. • Unless asked for, avoid using explicit loops if ever possible. • The total marks for this examination are 100 marks. Page 1 of 15 STATS 782 PART A 1. [10 Marks] Write down the evaluation results of the following R expressions, which are not necessarily meaningful in practice. [2 marks each] (a) 0:1 * 1:4 (b) if ({1;2} >= 3) {4;5} else {6;7} (c) NA | TRUE & ! FALSE (d) mean(0:9 > 7) (e) {s = 12; while(s > 5) s = s / 2; s} Answer: a. 0 2 0 4 b. 7 c. TRUE d. 0.2 e. 3 2. [6 Marks] Use :, seq(), rep() and some other commonly-used operators/- functions, but definitely not c() or a loop, to create the sequences below. [2 marks each] (a) 2 4 6 8 10 12 14 16 18 20 (b) 1 2 2 3 3 3 4 4 4 4 5 5 5 5 5 (c) “a1” “b1” “c1” “a2” “b2” “c2” “a3” “b3” “c3” Answer: a. 1:10 * 2 # or, seq(2, 20, by=2) b. rep(1:5, 1:5) c. paste0(letters[1:3], rep(1:3,each=3)) 3. [8 Marks] Write an R function named ldss() that finds and returns the (first) longest decreasing subsequence of a given sequence, where decreasing does not have to be strict. Taking the following sequence as an example, > x = c(69, 16, 92, 83, 13, 28, 68, 37, 19, 19) your function should perform as follows > ldss(x) # longest decreasing subsequence [1] 68 37 19 19 Page 2 of 15 STATS 782 Answer: ## The three lines in the function below find, respectively: ## (1) The index of the last element in each decreasing subsequence ## (2) The length of each decreasing subsequence, and then the index ## of the decreasing subsequence before the longest ## (3) The longest decreasing subsequence ldss = function(x) { i = c(0, which(diff(x) > 0), length(x)) im = which.max(diff(i)) x[(i[im]+1):i[im+1]] } 4. [8 Marks] Write an R function named nnc() such that, for each of the centres (given in an R vector center), finds and returns the number of x-values (given in an R vector x) that are nearest to it. Taking the following data as an example, > x = c(48, 13, 33, 31, 21, 16, 50, 17, 29, 78) > centre = c(20, 60, 100) your function should perform as follows > nnc(x, centre) centre count [1,] 20 7 [2,] 60 3 [3,] 100 0 The result means that 7 of the 10 values in x are nearest to center at 20 (of all three centres), 3 of them are nearest to centre at 60, and no x-value is nearest to centre at 100. Note that vectors x and center can be arbitrarily long. Answer: nnc = function(x, center) { xc = abs(outer(x, center, “-“)) i = apply(xc, 1, which.min) cbind(center=center, count=tabulate(i, nbins=length(center))) } Page 3 of 15

LATEST POSTS
MOST POPULAR

ezAce多年来为广大留学生提供定制写作、留学文书定制、语法润色以及网课代修等服务,超过200位指导老师为您提供24小时不间断地服务。