STAT 220: Basic Statistics for Quantitative Students

Spring 2006

Assignment due Jan. 20

First, login to ANGEL and locate the document describing R (this document has Companion in the title). Open this document.

This is a 177-page document. Do not print it! Also, this document was given to us by its author as a courtesy; as a courtesy to him, please do not make multiple copies of this file or email it to anyone.

Read Chapter 1, "Learning the Ropes". As you read, try the commands in R. Your job is to learn enough of the syntax of R to be able to complete the assignment below. You can download the files referred to in this chapter here.

Write four functions in R, as described below. Put them into a text file called "jan20.r" (if you use a program like MS Word for typing, don't forget to save the file as text). Attach this file to an email, then send it to the grader, Muhammad Atiyat <mxa934@psu.edu>. Note: You should not send output, only a single file containing the functions that may be "source"d into R and then tested by the grader.

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.

  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.

  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.

  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)
    

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