Hello, dear friend, you can consult us at any time if you have any questions, add WeChat: daixieit


Stats 20 Midterm 1 Practice Questions

Winter 2022


1: my_mean

The sample mean for a sample of values x = x1, x2, . . . , xn is defifined as

Write a function called my_mean() that computes the mean of a numeric vector x of data values without using the mean() function (or any other function that outputs the mean of some vector directly). Include an optional logical na.rm argument with a default value of FALSE that specififies whether to remove NA values from the computation.


2: Incorrect my_sign

Observe the following function:

(a)

What is the intended purpose of my_sign()? For what inputs x will there be no output of my_sign()? Why are there no outputs for these inputs?

Note: This question asks three questions – for full credit, one must answer all of them correctly.

(b)

Keeping the overall if statement structure (without additional flflow control, in other words, no additional if or else statements and no ifelse(), etc.), edit my_sign() so that it works as intended.

Note: For more practice, try to edit my_sign() with additional flflow control allowed.

(c)

Give example inputs that would cause my_sign() to throw:

• an error

• one or more warnings

(d)

Using the fifixed my_sign() function from (b), with a single command (e.g. one line of code), produce the output c("positive", "negative", "zero")


3: my_cumfun

Write a function called my_cumfun() that takes two inputs: x: a numeric vector, and fun: a function. my_cumfun() should compute the cumulative fun of x for the four functions sum, prod, max, min. The output of my_cumfun(x, sum), my_cumfun(x, prod), my_cumfun(x, max), my_cumfun(x, min) should be identical to the output of cumsum(x), cumprod(x), cummax(x), cummin(x) respectively.

Note: for more practice, add an argument na.rm with a default of FALSE that specififies whether or not to remove NA values from the computation of fun. Note that na.rm is an argument of all four possible values of fun: sum, prod, max, min. For even more practice, you can throw an error when an input for fun is none of the four possible values.


4: is.mode

is.logical() outputs TRUE if the storage mode of the input x is logical and FALSE otherwise. is.numeric() and is.character() work similarly. Write a function called is.mode() which takes as inputs x: an object, and mode: a length 1 character vector. The output of is.mode(x, mode) should be TRUE only if x has storage mode equal to the mode argument. You are disallowed from using is.logical(), is.numeric(), and is.character() in your is.mode() function. Additionally, throw an error with a message of your choosing if the input mode is not a character vector or has length not equal to one.

Note: each part would be considered “one” question on the exam. So question 2 is really four questions.