Instruction: Work with a neighbor to answer the following questions, then we will discuss the activity as a class. To get started, download the class activity template file.
The mean of numbers \(x_1,...,x_n\) is their average:
\[\frac{x_1 + x_2 + \cdots + x_n}{n}\]
In R, we can calculate the mean with the mean
function. For example:
## [1] 2
Write your own mean function, called my_mean
, that calculates the mean of a vector. The input to your function should be a vector, and the output should be the mean of the values in that vector. You may not use the built-in mean
function in R, but you may use the sum
and length
functions.
Check that your function works by comparing the output with R’s mean
function for several different input vectors.
A weighted mean is similar to the usual average, but now we add a weight to each value. The observations with greater weights contribute more to the weighted mean.
The weighted mean of \(x_1,...,x_n\) with weights \(w_1,...,w_n\) is
\[\frac{w_1 x_1 + w_2 x_2 + \cdots + w_n x_n}{w_1 + w_2 + \cdots + w_n}\] The usual arithmetic mean is a special case of the weighted mean with \(w_1 = w_2 = \cdots = w_n = 1\).
Modify your my_mean
function from Exercise 1 so that it now takes two inputs – a vector of values x
, and a vector of weights w
– and returns the weighted mean of x
with weights w
. Hint: If x
and w
are two vectors of the same length, then x*w
is a vector created by multiplying each entry of x
with the corresponding entry of w
.
When we calculate a mean, we usually don’t need weights. Modify your my_mean
function from Exercise 3 so that the default weights are all 1.
Check that your function from Exercise 4 works by running the following: