Hello, dear friend, you can consult us at any time if you have any questions, add WeChat: daixieit

ECON 4331w - Assignment 0

Created by: veronica postal & Hannes Malmberg

Updated on 01/18/2021

Getting started

The purpose of this assignment is to help you familiarize yourself with R and help you navigate the submission requirements for the data assignments in this course.

The exercise uses R and R studio.  Make sure you have downloaded these programs before starting.  For instructions on how to get started with R, please refer to section 1.4-1.6 in “R for Data science”.

You   should   submit   a   zipped-folder   with  your   assignment.      The   zip   folder   be   named   FiTst-

Name— LastName— AO.oip. It should contain at least three iles:

.  The script with your code, “FiTstName LastName AO.R 

.  An .Rproj ile called “FiTstName LastName AO.RpToj” (this will simply be a link to ensure that the grader sets it up in the right folder, see chapter 8 in “R for Data science”)

.  A pdf ile with the answers to all the exercises, “FiTstName— LastName AO.pdf.”  This ile should include written answers to each question (in English, no code) and/or the graphs that the exercise is asking you to generate.

In future assignments it is possible that you will have additional iles in your folder, like data iles or output iles. It is ine to have extra iles in your submission, but bear in mind that only the three iles listed above will be graded, so make sure to follow the instructions correctly.

The exercises below will walk you through how to create these iles. You are responsible for naming your iles appropriately, and that the code should run without errors (more on this below).

Basic Requirements

In order to succeed in this class, you will need to have a basic understanding of how to work with a computer. In particular, you need to be familiar with the following concepts:

1.  Directories (i.e. folders), their structure and hierarchy,

2.  Filepaths and why they are useful,

3.  File extensions.

Most people are already familiar with these concepts, but if you are unsure about any of these, please visit the resources linked below.

This page summarizes the most important information regarding directories and ilepaths.

The key thing about ile extensions is that you should not edit them to change your ile “type,” or you will create an error. You should also avoid typing them in when you are renaming your ile, whatever program you are using should automatically select the appropriate ile extension. This video explains the basics.

Step 1: creating  projects

one day you will need to quit R, go do something else and return to your analysis the next day. one day you will be working on multiple analyses simultaneously that all use R and you want to keep them separate. one day you will need to bring data from the outside world into R and send numerical results and igures from R back out into the world. To handle these real life situations, you need to make two decisions:

1. what about your analysis is “real”, i.e. what will you save as your lasting record of what happened?

2.  where does your analysis “live”?

What is real?

As a beginning R user, it,s ok to consider your environment (i.e. the objects listed in the environment pane) “real”. However, in the long run, you,ll be much better of if you consider your R scripts as“real”.  An R script  is simply a log of all the commands you have used to create your analysis or output.

with your R scripts (and your data iles), you can recreate the environment. It,s much harder to recreate your R scripts from your environment!  You,ll either have to retype a lot of code from memory  (making mistakes all the way) or you,ll have to carefully mine your R history.

To foster this behaviour, I highly recommend that you instruct Rstudio not to preserve your workspace between sessions:

 

This will cause you some short-term pain, because now when you restart Rstudio it will not remember the results of the code that you ran last time.  But this short-term pain will save you long-term agony because it forces you to capture all important interactions in your code. There,s nothing worse than discovering three months after the fact that you,ve only stored the results of an important calculation in your workspace, not the calculation itself in your code.

There is a great pair of keyboard shortcuts that will work together to make sure you,ve captured the important parts of your code in the editor:

1. press cmd/ctrl + shift + F1o to restart Rstudio.

2. press cmd/ctrl + shift + s to rerun the current script.

I use this pattern hundreds of times a week.

where does your analysis live?

R has a powerful notion of the working directory. This is where R looks for iles that you ask it to load, and where it will put any iles that you ask it to save. Rstudio shows your current working directory at the top of the console:

 

And you can print this out in R code by running getwd():

As a beginning R user, it,s Ok to let your home directory, documents directory, or any other weird directory on your computer be R,s working directory. But you,re six chapters into this book, and you,re no longer a rank beginner. very soon now you should evolve to organising your analytical projects into directories and, when working on a project, setting R,s working directory to the associated directory.

I do not recommend it, but you can also set the working directory from within R:

But you should never do this because there,s a better way; a way that also puts you on the path to managing your R work like an expert.

paths and directories

paths and directories are a little complicated because there are two basic styles of paths: Mac/Linux and windows. There are three chief ways in which they difer:

1.  The most important diference is how you separate the components of the path. Mac and Linux uses  slashes (e.g. plots/diamonds.pdf) and windows uses backslashes (e.g. plots\diamonds.pdf). R can  work with either type (no matter what platform you,re currently using), but unfortunately, backslashes  mean something special to R, and to get a single backslash in the path, you need to type two backslashes! That makes life frustrating, so I recommend always using the Linux/Mac style with forward slashes.

2. Absolute paths (i.e. paths that point to the same place regardless of your working directory) look diferent. In windows they start with a drive letter (e.g. C:) or two backslashes (e.g. \\servername) and in Mac/Linux they start with a slash“/”(e.g. /users/hadley). You should never use absolute paths in your scripts, because they hinder sharing: no one else will have exactly the same directory coniguration as you.

3.  The last minor diference is the place that ~ points to.  ~ is a convenient shortcut to your home directory. windows doesn,t really have the notion of a home directory, so it instead points to your documents  directory.


Rstudio projects

R experts keep all the iles associated with a project together — input data, R scripts, analytical results, igures. This is such a wise and common practice that Rstudio has built-in support for this via projects.

Let,s make a project for you to use while you,re working through the rest of this book.  click File 持 New

Project, then:

 

Make sure to use the “Browse””button (or to type a ilepath) to save your project in an appropriate location on your computer.

Section 1 Exercises

1.  (5 pts.)   create your R Project and call it Fir网tName-La网tName-AO.  Think carefully about which subdiTectoTg you put the project in. If you don,t store it somewhere sensible, it will be hard to ind it in the future!

once  this  process  is  complete,  you,ll  get  a  new  Rstudio  project  just  for  this  homework.     A project  is  constituted  by  a  new  folder  named  Fir网tName-La网tName-AO  and  by  a  ile  named Fir网tName-La网tName-AO.Rpro二.  Note that there is no need to manually type an extension here, R will do so automatically. The Rproj ile is essentially as a link to open a new R session for your project. whenever you start working on an assignment you should begin by clicking this link.

once this process is complete, you,ll get a new Rstudio project just for this homework.  check that the “home” directory of your project is the current working directory:


whenever you refer to a ile with a relative path it will look for it here.

2.  (5 pts.)  copy the following commands in the R  Console  (in the bottom left corner when you open R studio) and click enter. This will create a graph called diamonds.pdf and it will save into your project directory. Don,t worry about the details of this code, you,ll learn them later in the course. Normally you would be expected to add all graphs to your write-up and all code in the script, but since we are just getting started with R, do not worry about this now. Just make sure that the graph is correctly saved to your project folder to get full credit for this question.

To conirm this exercise was done correctly, in your favorite os-speciic way, search your computer for diamonds.pdf to make sure that the PDF is in your project folder.

Quit Rstudio. Inspect the folder associated with your project — notice the  .Rpro二 ile.  Double-click that ile to re-open the project.  Notice you get back to where you left of: it,s the same working directory and command history, and all the iles you were working on are still open. Because you followed my instructions above, you will, however, have a completely fresh environment, guaranteeing that you,re starting with a clean slate.

summary

In summary, Rstudio projects give you a solid worklow that will serve you well in the future:

.  create an Rstudio project for each data analysis project.

.  keep data iles there; we,ll talk about loading them into R in [data import].

.  keep scripts there; edit them, run them in bits or as a whole.

.  save your outputs (plots and cleaned data) there.

.  only ever use relative paths, not absolute paths.

step 2: create a script

A script is simply a text ile were you can keep all the code that you used to generate your output. using scripts is crucial in any professional setting because they allow us to quickly reproduce output when needed and they also make it possible to verify that all steps taken in producing the output are correct.

Furthermore, using a script means that everything you need is in one place, and cleanly separated from all the other projects that you are working on.  open up a new script either by clicking the File menu, and selecting New File, then R script, or using the keyboard shortcut cmd/ctrl + shift + N.

 

You should now see something like this:

 

The pane in the upper left corner is your script Editor, while the pane in the lower left corner is the console.

The script editor is a great place to put code you care about.  keep experimenting in the console, but once you  have written code that works and does what you want, put it in the script editor. Rstudio will automatically save the contents of the editor when you quit Rstudio, and will automatically load it when you re-open. Nevertheless, it,s a good idea to save your scripts regularly and to back them up.

section 2 Exercises

1.  (2.5 pts.)  save your script (File 持 save As) and call it FirstName-LastName-AO.R. Make sure to save this in your R Project folder. Again, there is no need to manually type a ile extension here, R will do so automatically.

keep editing the script throughout this exercise as needed. Make sure to save your work when you are

done by clicking File 持 save or using the keyboard shortcut cmd/ctrl + s.

2.  (5 pts.)  All code that you use to create your assignment should appear in a script and everything in a script needs to be code.

sometime it is useful to annotate the code to separate it into section or to elucidate what the code is meant to do. Everything that is not a piece of code is called a comment, and each line of comments needs to start with a“论”so that when running the script R knows to skip over that line and will not attempt executing your comments as if they were commands.

It is best practice to start a script with a comment detailing the script,s author and the purpose of the script. It is also important to use comments to section of your script into diferent exercises or to provide guidance on complicated pieces of code (if needed.)

please do so for your own script. It should look similar to the image below (but it should contain your own name and the correct date, etc.):

 

3.  (2.5 pts.)  please copy the following statement in your script:

 

4.  (5 pts.)  In this class, you,ll often need to install R packages.  An R package is a collection of functions, data, and documentation that extends the capabilities of base R. using packages is key to the successful use of R. The majority of the packages that you will learn in this course are part of the so-called tidyverse. The packages in the tidyverse share a common philosophy of data and R programming, and are designed to work together naturally.

You can install the complete tidyverse with a single line of code:

The install.packages command needs to be done only once in your computer,s lifetime.  For this reason install.packages statements do not belong in the script.

since you have already installed this package in Exercise 1.2, there is no need to do so again.  In general, if  you want to install a new package on your computer, you can type install.packages("package-name") in the console, and then press enter to run it. R will download the packages from cRAN and install  them on to your computer. If you have problems installing, make sure that you are connected to the  internet, and that https://cloud.r-project.org/ isn,t blocked by your irewall or proxy.

You will not be able to use the functions, objects, and help iles in a package until you load it with library() . once you have installed a package, you can load it with the library() function:

##  -- Attaching packages  --------------------------------------- tidyverse  1.3.1  --

## v ggplot2  3.3.6         v purrr     0.3.4

## v tibble   3.1.7        v  dplyr     1.0.9

## v tidyr     1.2.0        v  stringr  1.4.0

## v readr     2.1.2         v  forcats  0.5.1

##  --  conflicts  ------------------------------------------ tidyverse-conflicts()  --

## x dplyr::filter()  masks  stats::filter()

## x dplyr::lag()        masks  stats::lag()

Add this library statement to your script, just below the ###  Load  packages comment.  It is best practice to load all packages using library() statements at the top of your script, after the heading but before the rest of the code.

Note that the library import statement needs to be repeated in each new script if you are planning to use the functions contatined in a particular package.

5.  (5 pts.)  Install the gapminder package through the console and add gapminder to the library import statements at the top of your script.

step 3: create a write-Up for your Assignment

The write up is were you summarize your answers. This is not necessary for all questions, but in general if you feel the need to answer a question in English rather than only using a piece of code, the place to do so is the write-up. All output, such as graphs and tables should also be included in your write up.

You can use your preferred text editor, for example Microsoft word, to write the write-up. please make sure to include your name at the top of your write-up and to number your answers.

section 3 Exercises

1.  (5 pts.)  create a ile for your write-up.  start it with your name, date and assignment number.  when  you are done with this assignemt, save it by clicking File 米 save As and selecting pdf as the ile type. Name this ile FirstName-LastName-A0.

 

objects

R has a powerful notion of objects. Everything you see or create in R is an object. A vector, matrix, data frame, even a variable is an object. R treats it that way.

Creating an object is really easy in R. The object assignment statement is <-. At the left of the arrow you should type the obejct name to distinguish it from other objects in memory, while at the right of the arrow you should have some sort of statement that .  For example try typing in your console:

The irst statement will make an object appear in your environment. This object will be called x and it will contain a single number, 5. The second statement will create an object called 处 that contains all numbers from 1 to 1o.

If you are producing some output, for example a graph, R might show you a “snapshot” of what your graph will look like, but it won,t save in your environment unless you create an object. This means you will not be able to access that output later if needed.

section 4 Exercises

1.  (5 pts.)  Copy the code below in your script.

Explain in your write up what happens when you run the irst line of code. what happens when you run the second line? what is the diference?

step 4: checking your work

warnings and Errors

There are two types of feedback R might give you after you run a piece of code:

warnings: A warning tends to be a notice that does not imply a fatal error, but that is alerting you that something could go wrong or might not work in the future. In general it is best practice to pay attention to warnings and to be aware of what they say, but it is okay if the code you submit generates warnings.

Errors: An error means that something went wrong, either recoverably or unrecoverably. A recoverable error is one after which the program can (probably) still continue whereas an unrecoverable error is one which causes the program to ‘hang, or ‘crash,. when you submit your script, it is expected it will run error free or you will incur a penalty.

If you get an error, start by checking doing the following:

1.  check your spelling.  Programming requires a lot of attention to be paid to how things are written. code is case sensitive, and even little things like an extra )or " can cause an error.

2.  check Google. Being self reliant and learning how to debug your own code is a fundamental skill. If you search for your error online you should be able to ind dozen of resources on the topic.

How to Make sure your code Runs Error Free

once you are done with your assignment, save your script.  Everything that is worth saving should be included there. Then either re-start a new session of R Studio or erase your environment:

 

Then click cmd/ctrl + A and cmd/ctrl + Enter to re-run the entire thing.  keep an eye out to make sure that R doesn,t raise any errors.

The two typical mistakes that students make at this stage are the following:

1.  Forgetting to include library statements.

2.  Forgetting to save data iles in their folder.

If your code runs without errors, your are good to go and you can proceed to the next step.

step 5: zip your folder and upload to canvas

once you are done working on your homework, it is time to save your script and your write-up. Then zip the folder you are working from; it should be named your FirstName-LastName-AO if you named it correctly when creating your R Project.

If you are unsure on how to zip (or unzip a folder), or what a compressed ile is, please review this video it has instructions for both Mac and windows operating systems.

canvas will only accept a single zipped ile as a submission, so if you are encountering an upload error, you probably zipped your folder incorrectly.

using R Markdown

using R Markdown to complete your assignment is allowed but not encouraged unless you are proicient with it. If you are unfamiliar with R Markdown, please ignore these submission instructions.

For a submission with R Markdown you will still need to submit a zipped-folder with your assignment. The zip folder be named FiTstName— LastName— AO.oip. It should contain at least three iles:

.  The script ile for R Markdown, FiTstName LastName AO.Rmd 

.  An .Rproj ile called “FiTstName LastName AO.RpToj 

.  A pdf version of your script, “FiTstName LastName AO.pdf.”