+ - 0:00:00
Notes for current slide
Notes for next slide

ETC1010: Data Modelling and Computing

Lecture 6A: Style, file paths, & functions

Dr. Nicholas Tierney & Professor Di Cook

EBS, Monash U.

2019-09-04

1 / 39

Recap

  • Missing Data
  • Web Scraping
2 / 39

Upcoming due dates

  • Assignment 3: Thursday 26th September (Released 12th September)
  • Practical Exam: 16th October (see practice exam on dmac)
  • Project: 18th October (See examples of past projects)
3 / 39

Practical Exam?

  • A live data analysis
  • 1 Hour
  • See example on website
4 / 39

Project?

  • Collect / find your own data
  • Clean the data
  • Determine interesting questions to answer about the data
  • Plan how to execute analysis of the data
  • Communicate the idea, data cleaning, and analysis (oral presentation)
  • Further details are on the dmac website
5 / 39

Lecture Overview

  • Coding style
  • File paths and Rstudio projects
  • (Intro to) Using functions
6 / 39

Style guide

"Good coding style is like correct punctuation: you can manage without it, butitsuremakesthingseasiertoread." -- Hadley Wickham

  • Style guide for this course is based on the Tidyverse style guide: http://style.tidyverse.org/
  • There's more to it than what we'll cover today, we'll mention more as we introduce more functionality, and do a recap later in the semester
7 / 39

File names and code chunk labels

  • Do not use spaces in file names, use - or _ to separate words
  • Use all lowercase letters
# Good
ucb-admit.csv
# Bad
UCB Admit.csv
8 / 39

Object names

  • Use _ to separate words in object names
  • Use informative but short object names
  • Do not reuse object names within an analysis
# Good
acs_employed
# Bad
acs.employed
acs2
acs_subset
acs_subsetted_for_males
9 / 39

Spacing

  • Put a space before and after all infix operators (=, +, -, <-, etc.), and when naming arguments in function calls.
  • Always put a space after a comma, and never before (just like in regular English).
# Good
average <- mean(feet / 12 + inches, na.rm = TRUE)
# Bad
average<-mean(feet/12+inches,na.rm=TRUE)
10 / 39

ggplot

  • Always end a line with +
  • Always indent the next line
# Good
ggplot(diamonds, mapping = aes(x = price)) +
geom_histogram()
# Bad
ggplot(diamonds,mapping=aes(x=price))+geom_histogram()
11 / 39

Long lines

  • Limit your code to 80 characters per line. This fits comfortably on a printed page with a reasonably sized font.
  • Take advantage of RStudio editor's auto formatting for indentation at line breaks.
12 / 39

Assignment

  • Use <- not =
# Good
x <- 2
# Bad
x = 2
13 / 39

Quotes

Use ", not ', for quoting text. The only exception is when the text already contains double quotes and no single quotes.

ggplot(diamonds, mapping = aes(x = price)) +
geom_histogram() +
# Good
labs(title = "`Shine bright like a diamond`",
# Good
x = "Diamond prices",
# Bad
y = 'Frequency')
14 / 39

Your Turn: ed

  • Go to ed and assess your understanding of code style (there may be some technical difficulty)
15 / 39

File Paths and organising yourself

  • It's important when you start working on your own machine that you understand file storage hygiene.
  • It helps prevent unexpected problems and makes you more productive
  • You'll spend less time fighting against strange file paths.
  • Not sure what a file path is? We'll explain that as well.
16 / 39

Your Turn

Discuss:

  1. What your normal "workflow" is for starting a new project
  2. Possible challenges that might arise when maintaining your project
17 / 39

A Mantra: When you start a new project - Open a new RStudio project

setwd("c:/really/long/file/path/to/this/directory)
  • What do you think the setwd code does?
18 / 39

What does setwd() do?

  • "set my working directory to this specific working directory".

  • It means that you can read in data and other things like this:

data <- read_csv("data/mydata.csv")
  • Instead of
data <- read_csv("c:/really/long/file/path/to/this/directory/data/mydata.csv")
19 / 39

What even is a file path?

  • This has the effect of making the file paths work in your file
  • This is a problem because, among other things, using setwd() like this:
    • Has 0% chance of working on someone else's machine (this includes you in >6 months)
    • Your file is not self-contained and portable. (Think: "What if this folder moved to /Downloads, or onto another machine?")
  • To get this to work, you need to hand edit the file path to your machine.
  • This is painful. And when you do this all the time, it gets old, fast.
20 / 39

What even is a file path?

  • This all might be a bit confusing if you don't know what a file path is.
  • A file path is: "the machine-readable directions to where files on your computer live."
  • So, this file path:
/Users/njtierney/rmd4sci-materials/demo-gapminder.Rmd

Describes the location of the file "demo-gapminder.Rmd".

21 / 39

What even is a file path

We could visualise the path

/Users/njtierney/rmd4sci-materials/demo-gapminder.Rmd

as:

users
└── njtierney
└── rmd4sci-materials
└── demo-gapminder.Rmd
22 / 39
  • To read in the gapminder.csv file, you might need to write code like this:
gapminder <- read_csv("/Users/njtierney/Desktop/rmd4sci-materials/data/gapminder.csv")

This is a problem, because this is not portable code.

23 / 39

If you have an RStudio project file inside the rmd4sci-materials folder, you can instead write the following:

gapminder <- read_csv("data/gapminder.csv")
24 / 39

Your Turn

  • (1-2 minutes) What folders are above the health.csv file in the following given file path?

"/Users/miles/etc1010/week1/data/health.csv"

25 / 39

Your Turn

  • What would be the result of using the following code in demo-gapminder.Rmd, and then using the code, and then moving this to another location, say inside your C drive?
setwd("Downloads/etc1010/week1/week1.Rmd)
26 / 39

Is there an answer to the madness?

  • This file path situation is a real pain.
  • Is there an answer to the madness?
27 / 39

Is there an answer to the madness?

  • This file path situation is a real pain.
  • Is there an answer to the madness?

The answer is yes!

I highly recommend when you start on a new idea, new research project, paper. Anything that is new. It should start its life as an rstudio project.

27 / 39

Rstudio projects

An rstudio project helps keep related work together in the same place. Amongst other things, they:

  • Keep all your files together
  • Set the working directory to the project directory
  • Starts a new session of R
  • Restore previously edited files into the editor tabs
  • Restore other rstudio settings
  • Allow for multiple R projects open at the same time.
28 / 39

Rstudio projects

This helps keep you sane, because:

  • Your projects are each independent.
  • You can work on different projects at the same time.
  • Objects and functions you create and run from project idea won't impact one another.
  • You can refer to your data and other projects in a consistent way.

And finally, the big one

RStudio projects help resolve file path problems, because they automatically set the working directory to the location of the rstudio project.

29 / 39

The "here" package

  • RStudio projects help resolve file path problems
  • In some cases you might have many folders in your r project. To help navigate them appropriately, you can use the here package to provide the full path directory, in a compact way.
here::here("data")

returns

[1] "/Users/njtierney/Desktop/rmd4sci-materials/data"
30 / 39

The here package

here::here("data", "gapminder.csv")

returns

[1] "/Users/njtierney/Desktop/rmd4sci-materials/data/gapminder.csv"

You can read the above here code as:

In the folder data, there is a file called gapminder.csv, can you please give me the full path to that file?

31 / 39

The here package

This is really handy for a few reasons:

  1. It makes things completely portable
  2. Rmarkdown documents have a special way of looking for files, this helps eliminate file path pain.
  3. If you decide to not use RStudio projects, you have code that will work on any machine
32 / 39

Remember

If the first line of your R script is

setwd("C:\Users\jenny\path\that\only\I\have")

I will come into your office and SET YOUR COMPUTER ON FIRE 🔥.

-- Jenny Bryan

33 / 39

Aside: How to create an RStudio project

34 / 39

Summary of file paths and rstudio projects

In this lesson we've:

  • Learnt what file paths are
  • How to setup an rstudio project
  • How to construct full file paths with the here package
35 / 39

Motivating Functions

36 / 39

Do you see any problems with this code?

st_episode <- st %>%
html_nodes(".np_right_arrow .bp_sub_heading") %>%
html_text() %>%
str_replace(" episodes", "") %>%
as.numeric()
got_episode <- got %>%
html_nodes(".np_right_arrow .bp_sub_heading") %>%
html_text() %>%
str_replace(" episodes", "") %>%
as.numeric()
twd_episode <- got %>%
html_nodes(".np_right_arrow .bp_sub_heading") %>%
html_text() %>%
str_replace(" episodes", "") %>%
as.numeric()
37 / 39

Next Lecture: Why functions?

  • Automate common tasks in a power powerful and general way than copy-and-pasting:
    • You can give a function an evocative name that makes your code easier to understand.
    • As requirements change, you only need to update code in one place, instead of many.
    • You eliminate the chance of making incidental mistakes when you copy and paste (i.e. updating a variable name in one place, but not in another).
38 / 39

Next Lecture: Why functions?

  • Automate common tasks in a power powerful and general way than copy-and-pasting:
    • You can give a function an evocative name that makes your code easier to understand.
    • As requirements change, you only need to update code in one place, instead of many.
    • You eliminate the chance of making incidental mistakes when you copy and paste (i.e. updating a variable name in one place, but not in another).
  • Down the line: Improve your reach as a data scientist by writing functions (and packages!) that others use
38 / 39

Share and share alike

Creative Commons License
This work is licensed under a Creative Commons Attribution 4.0 International License.

39 / 39

Recap

  • Missing Data
  • Web Scraping
2 / 39
Paused

Help

Keyboard shortcuts

, , Pg Up, k Go to previous slide
, , Pg Dn, Space, j Go to next slide
Home Go to first slide
End Go to last slide
Number + Return Go to specific slide
b / m / f Toggle blackout / mirrored / fullscreen mode
c Clone slideshow
p Toggle presenter mode
t Restart the presentation timer
?, h Toggle this help
Esc Back to slideshow