STAT 220: Basic Statistics for Quantitative Students

Spring 2006

SOLUTIONS FOR Assignment due Jan. 20

Below are the four functions you should write. You are not required to use the suggestions given as "hints" to complete the assignment, but they might help.
  1. Write a function called addseq. It should take a single argument, a vector of length 3. It should add the vector c(1, 2, 3) to its argument and return the result. Sample output:
    > x=c(6,3,9)
    > addseq(x)
    [1]  7  5 12
    
    Hint: This function can be written using only a single argument.

    Answer:
    addseq = function(a) c(1,2,3)+a

  2. Write a function called reverse. It should take a single argument, a vector of arbitrary length. It should then return the vector with its order reversed. Sample output:
    > x=c(1, 2, 8:4)
    > x
    [1] 1 2 8 7 6 5 4
    > reverse(x)
    [1] 4 5 6 7 8 2 1
    
    Hint: Use the length function and the seq function. You will also need the material in the "Optional: Indexing" section starting on page 17.

    Answer:
    reverse = function(a) a[length(a):1]

  3. Write a function called addmulthyp. It should take two arguments, say x and y, and return a vector containing three elements: their sum, their product, and the length of the hypotenuse of a right triangle with legs x and y. Sample output:
    > addmulthyp(3,4)
    [1]  7 12  5
    > addmulthyp(1,1)
    [1] 2.000000 1.000000 1.414214
    
    Hint: Use the sqrt function. Look up its help file if you need to.

    Answer:
    addmulthyp = function(x, y) c(x+y, x*y, sqrt(x^2+y^2))

  4. Write a function called tableplot. It should take one argument. The argument will be a data.frame with columns named "volumes" and "expend", like the "a" object shown at the bottom of page 12. The function should produce a scatterplot of these two columns. The x-axis should be labeled "volumes" and the y-axis should be labeled "expend". The title of the plot should read "volumes vs. expend". Sample output:
    > a = read.csv("univ-libraries.csv")
    > tableplot(a)
    

Answer:
tableplot = function(x) plot(x[,"volumes"], x[,"expend"], xlab="volumes", ylab="expend", main="volumes vs. expend")

If you want to look at some example R functions, check out the files rcompfunctions.r and dice.r in this directory.