Lab Assignment 2
February 1st
In this assignment you will:
- Review and practice basic syntax in R - Practice basic operations using vectors and functions
Getting Started:
- In RStudio select FILE (or use the + button) -> NEW FILE -> R Notebook
- In the YAML/header do the following:
- Replace “R Notebook” with “Lab Assignment 2”
- Add the following 2 lines immediately below title: “Lab Assignment 2”
- author: “Your name here”
- date: “The date when you create the file here”
- Save your file as YOURLASTNAME_Lab2 in the folder you created for this class in the last assignment
- In RStudio go to HELP -> CHEATSHEETS -> “R Markdown Reference Guide”. This will help you answer any R Markdown questions you may have.
Instructions:
Respond to each of the questions in your R Notebook file. When you are finished, make sure you have run all the code chunks. Then preview the document (do so along the way to check your progress) and upload the .Rmd file and the nb.html file to Canvas. Make sure you name your file using the following format: YOURLASTNAME_LabX.
For each question, include the question numberQuestion Xbefore inserting any code chunks or answering questions. You do not need to rewrite the question.
Question 1:After saving your notebook, insert a code chunk and print your current working directory by using the function getwd().
Question 2:In the table below are votes cast for both major party candidates in the 2016 recent presidential election for a random sample of states (every fifth alphabetically). Insert a code chunk that creates a vector of Trump votes. Name it something intuitive. Repeat for Clinton votes. Check your work by listing each vector.
State Name |
Trump Vote Count |
Clinton Vote Count |
---|
Alabama |
1,318,255 |
729,547 |
California |
4,483,814 |
8,753,792 |
Florida |
4,617,886 |
4,504,975 |
Indiana |
1,557,286 |
1,033,126 |
Maine |
335,593 |
357,735 |
Mississippi |
700,714 |
485,131 |
New Hampshire |
345,790 |
348,526 |
Ohio |
2,841,006 |
2,394,169 |
South Carolina |
1,155,389 |
855,373 |
Vermont |
95,369 |
178,573 |
Wyoming |
174,419 |
55,973 |
Question 3:Continuing to work with the 2016 election results, insert a code chunk that computes thepercentof the vote Clinton won in each state and assign them to a vector. Check your work by printing out the vector.
Question 4:Generate a vector that contains the state names and assign the results to Clinton’s percent of the vote (the vector you created in previous question) using thenames()
function. Print Clinton’s vote percent.
Question 5:Insert a chunk of code that produces a new vector that gives the share of the vote won by Clinton in each state that she won (but no others) using the which() function. Print out the vector. In another codechunk, create another vector with the share of votes won by Clinton in each state that she won by manually selecting out those states using index c(). Print out the new vector.