Exercise 2: Coding Habits & Functions#

This assignment will give you some practice writing your own functions and using the coding best practices discussed in the tutorial.


1. Summary statistics (4 pts)#

Write a function that takes a vector of numbers x and returns the length, mean, and standard deviation of x as a new vector.

In keeping with our best practices, give the function a short but descriptive name, and use snake case if it involves multiple words.

Hint: Vectors are defined in R using the c() command.

#Write your function here

Calculate the summary statistics of vector v1.

Hint: Note the “NA” in the vector. This is short for “not available” and is a placeholder for missing values. You’ll want to look up the is.na function (and the not operator !), as well as options for removing NA’s in the functions that you will use to summarize the vector. Look at the documentation for the functions that you will use to see how to work with NA’s.

v1  <- c(5, 11, 6, NA, 9)

#your_function_name(v1)

2. T-test function (4 pts)#

The formula for a t-test is:

\[ \frac{m- \mu}{ \frac{s}{\sqrt{n}}} \]

Where m is the sample mean, \(\mu\) (mu) is the population mean, s is the standard deviation, and n is the sample size.

Using your function above as a starting point, write a new function ttest_fun that compares a vector x to a given population mean mu and calculates the t-statistic. Keep the coding best practices in mind.

Hint: You will need to add another argument for mu.

# Write ttest_fun here

Use your function to compare the mean of v1 to 10.

ttest_fun(v1, 10)

3. Setting default values (2 pts)#

Set the default value of mu to 0. Test your modified function below by supplying only v2 as an argument.

# Write your modified ttest_fun here
v2 <- c(3, 7, 1, NA, 8, 12)
ttest_fun(v2)

How does your result compare to R’s built-in t.test() function?

t.test(v2)

When you are finished, save the notebook as Exercise2.ipynb, push it to your class GitHub repository (the one you made for Exercise 1) and send the instructors a link to your notebook via Canvas. You can send messages via Canvas by clicking “Inbox” on the left and then pressing the icon with a pencil inside a square.

DUE: 5pm EST, Feb 5, 2024

IMPORTANT Did you collaborate with anyone on this assignment? If so, list their names here.

Someone’s Name