This assignment is intended to practice making functions, loops/iterations, and logical conditions/vectors. Assessment is effort/completion based. The assignment is meant to be a practice and learning tool, and is not busy work to justify grade points. Ultimately, whether you use outside assistance to complete this assignment is not necessarily something I can prevent, but repeatedly offloading these tasks through outside assistance may result in weak coding skills that make the rest of the class frustrating.
For this assignment you should edit the “author” info in the header to include your name. Note that you should save your file as “HW2_Your_Name.Rmd” when knitting.
For each question, you should add or modify code in blocks provided. You should provide any written responses in the section that follows the code block. Knit after each question
If code for a question has been provided, but you were not asked to modify it, please don’t delete it or your .Rmd file might not knit properly.
Homework #2 is due Wednesday 9/30 by 11:59pm. A 4th question will be added on Friday 9/25
A quantitative variable can be rescaled so that its smallest value is \(a\) and its largest value is \(b\) using
\[ a + (b-a)\frac{x-\min(x)}{\max(x)-\min(x)}. \]
A. Write a function called rescale()
with arguments x, lower, and
upper. The function should rescale the values of
x using the formula above.
Set the default value of lower equal to 0 and the
default value of upper equal to 1.
B. Test your function on the following vector:
x = c(12, 18, 25, 31, 42, 47)
First use the default values of lower and
upper. Then use your function to rescale x to
values between 0 and 100. Then rescale x using an upper
bound of 10, but no specified lower bound. Do all of these work?
A common way to standardize a quantitative variable (x) is to subtract some measure of its center and divide by some measure of its spread:
\[ z_i = \frac{x_i-\text{center}}{\text{spread}}. \]
Typically, we use the sample mean ({x}) for the center and the sample standard deviation (s_x) for the spread. However, there may be situations where we want to supply different values for the center or spread.
A: (Rehash of lab exercise) Write a function called
standardize that standardizes a supplied vector. It should
use 3 arguments x, center,
spread, and should default to sample statistic values for
each measure.
B: Another common rule identifies potential outliers
based on the absolute value of their standardized values. Write a
function called is_outlier() that takes the two arguments
z (vector of standardized values) and cutoff,
which is a supplied value we must give the function, and then the
function tells us whether a value is an outlier based on the
cutoff.
Your function should return TRUE whenever the absolute
value of a standardized observation exceeds the supplied cutoff and
FALSE otherwise.
C: Use your standardize() and
is_outlier() functions together to identify observations of
the following vector whose standardized values exceed 2 in absolute
value. Use the default values for center and spread.
scores = c(Maya = 82, David = 68, Carlos = 75, Aisha = 71, Emily = 69, Fatima = 84, Marcus = 85, Priya = 71, Luis = 49, Hannah = 77)
D: Store the logical vector returned by
is_outlier in the previous question. Write code to
determine the following without using magic numbers:
E: Repeat the analysis using a cutoff of 1. How does decreasing the cutoff affect the observations identified as potential outliers?
colleges <- read.csv("https://nfriedrichsen.github.io/data/Colleges2019.csv")
Suppose we are interested in comparing the prevalence of relatively
selective colleges across different regions of the United States. For
this question, we will define a relatively selective
college as one with an admission rate (Adm_Rate)
below 50%.
A: Using logical conditions and subsetting, find the
proportion of colleges in the "Great Lakes" region that
have an admission rate below 50%.
B: We could repeat the calculation from Part A separately for every region, but this would require writing essentially the same code many times. Instead, create the following object:
unique_regions = unique(colleges$Region)
Create an empty numeric vector called selective_prop
with one position for each region.
C: Write a for loop that goes through
each value in unique_regions. For each region:
colleges to contain only colleges from that
region.selective_prop.D: Give the values in selective_prop
names corresponding to their regions.
Which regions have the largest and smallest proportions of relatively selective colleges?
An indicator variable is a numeric variable that
takes the value 1 when an observation satisfies some
condition and 0 otherwise. Indicator variables are commonly
used to represent categorical information numerically.
For example, the following code creates an indicator variable identifying colleges located in the Plains region:
as.numeric(colleges$Region == "Plains")
The logical condition first produces TRUE or
FALSE for each college. The as.numeric()
function then converts TRUE to 1 and
FALSE to 0.
A: Create a function named
make_indicator() that takes two arguments:
x: a categorical variablecategory: a particular category of interestThe function should return a numeric indicator vector that equals
1 when x belongs to category and
0 otherwise.
Test your function using colleges$Region and
"Plains".
B: Use unique() to create a vector
named regions containing the different values of
Region in the colleges data.
We would now like to create an indicator variable for every region rather than writing the same code separately for each one.
Create an empty data frame with the correct number of rows using:
region_indicators = data.frame(
row_number = 1:nrow(colleges))
Then use a for loop to apply your
make_indicator() function to every value in
regions. Store each resulting indicator as a new column of
region_indicators.
You can use the following structure to create a column whose name is
determined by the current value of region:
region_indicators[[region]] = # your code here
The row_number variable was only used to initialize our
data frame with the correct number of rows. After your loop, remove it
using:
region_indicators$row_number = NULL
When you are finished, use head(region_indicators) to
examine your results.
C: The names of these variables currently contain only the name of each region. We would like the variable names to make it clear that they are indicator variables.
The paste0() function can be used to combine character
strings:
paste0("Plains", "_Ind")
which returns "Plains_Ind".
First, save the current column names using:
region_names = colnames(region_indicators)
Then use a for loop to rename each column by adding
"_Ind" to the end of its original name. You can change an
individual column name using:
colnames(region_indicators)[i] = # new name
Finally, print colnames(region_indicators) to verify
that your columns have been renamed appropriately.