1.3 Introduction to Programming

Reading In Data (continued)

Reading in a CSV file

CSV

Comma Separated Value. Different columns are separated by comma characters (,). Any field that contains a comma must be quoted.

library(readr)

carbon_df <- read_csv(files[3])
names(carbon_df) <- c("Year", "TotalC")
head(carbon_df)
1
Read in the third file in the list, which ends in carbon_emissions.csv
2
Rename columns to have shorter names
3
Look at the head (the first 6 rows, by default) of the object
# A tibble: 6 × 2
   Year TotalC
  <dbl>  <dbl>
1  1751      3
2  1752      3
3  1753      3
4  1754      3
5  1755      3
6  1756      3

File contents

 [1] "Year,Total carbon emissions from fossil fuel consumption and cement production (million metric tons of C)"
 [2] "1751,3"                                                                                                   
 [3] "1752,3"                                                                                                   
 [4] "1753,3"                                                                                                   
 [5] "1754,3"                                                                                                   
 [6] "1755,3"                                                                                                   
 [7] "1756,3"                                                                                                   
 [8] "1757,3"                                                                                                   
 [9] "1758,3"                                                                                                   
[10] "1759,3"                                                                                                   

More Complicated CSVs

olive_df <- read_csv(files[8])
1
Try reading in the olive data from CSV
New names:
Rows: 572 Columns: 11
── Column specification
──────────────────────────────────────────────────────── Delimiter: "," chr
(2): Region, eicosenoic dbl (9): ...1, Area, palmitic, palmitoleic, stearic,
oleic, linoleic, linole...
ℹ Use `spec()` to retrieve the full column specification for this data. ℹ
Specify the column types or set `show_col_types = FALSE` to quiet this message.
• `` -> `...1`

Warning: One or more parsing issues, call problems() on your data frame for details, e.g.:

dat <- vroom(...)

problems(dat)

More Complicated CSVs

problems(olive_df)
1
When a CSV is not properly formatted, problems can pile up. Use problems() to see what R is complaining about.
# A tibble: 572 × 5
     row   col expected   actual     file                                       
   <int> <int> <chr>      <chr>      <chr>                                      
 1     2    12 11 columns 12 columns /home/susan/R/x86_64-pc-linux-gnu-library/…
 2     3    12 11 columns 12 columns /home/susan/R/x86_64-pc-linux-gnu-library/…
 3     4    12 11 columns 12 columns /home/susan/R/x86_64-pc-linux-gnu-library/…
 4     5    12 11 columns 12 columns /home/susan/R/x86_64-pc-linux-gnu-library/…
 5     6    12 11 columns 12 columns /home/susan/R/x86_64-pc-linux-gnu-library/…
 6     7    12 11 columns 12 columns /home/susan/R/x86_64-pc-linux-gnu-library/…
 7     8    12 11 columns 12 columns /home/susan/R/x86_64-pc-linux-gnu-library/…
 8     9    12 11 columns 12 columns /home/susan/R/x86_64-pc-linux-gnu-library/…
 9    10    12 11 columns 12 columns /home/susan/R/x86_64-pc-linux-gnu-library/…
10    11    12 11 columns 12 columns /home/susan/R/x86_64-pc-linux-gnu-library/…
# ℹ 562 more rows

More Complicated CSVs

readLines(files[8])[1:10]
1
When in doubt, look at the first few lines of the file. Count how many columns in several rows manually. Then come up with a hypothesis and a plan.
 [1] ",Region,Area,palmitic,palmitoleic,stearic,oleic,linoleic,linolenic,arachidic,eicosenoic"
 [2] "1,North-Apulia,1,1,1075,75,226,7823,672,36,60,29"                                       
 [3] "2,North-Apulia,1,1,1088,73,224,7709,781,31,61,29"                                       
 [4] "3,North-Apulia,1,1,911,54,246,8113,549,31,63,29"                                        
 [5] "4,North-Apulia,1,1,966,57,240,7952,619,50,78,35"                                        
 [6] "5,North-Apulia,1,1,1051,67,259,7771,672,50,80,46"                                       
 [7] "6,North-Apulia,1,1,911,49,268,7924,678,51,70,44"                                        
 [8] "7,North-Apulia,1,1,922,66,264,7990,618,49,56,29"                                        
 [9] "8,North-Apulia,1,1,1100,61,235,7728,734,39,64,35"                                       
[10] "9,North-Apulia,1,1,1082,60,239,7745,709,46,83,33"                                       

CSV Trick: Separate the Names from the Data

olive_df <- read_csv(files[8],
                     col_names = FALSE,
                     skip = 1)
olive_names <- read_csv(files[8], col_names = FALSE, n_max = 1)
olive_names <- as.character(olive_names)
olive_names <- c("row", "RegionName", olive_names[-1])
names(olive_df) <- olive_names
head(olive_df)
1
Read in the same file, but with additional arguments
2
Tell read_csv you’re not providing column names
3
Skip the first line of the file
4
Read in only the first line of the file
5
Convert the table to a vector (a list)
6
Add names for the first two columns (row, RegionName) and remove the empty entry (olive_names[-1]). Put everything into the same vector using c(...)
7
Set the names of the table
# A tibble: 6 × 12
    row RegionName   Region  Area palmitic palmitoleic stearic oleic linoleic
  <dbl> <chr>         <dbl> <dbl>    <dbl>       <dbl>   <dbl> <dbl>    <dbl>
1     1 North-Apulia      1     1     1075          75     226  7823      672
2     2 North-Apulia      1     1     1088          73     224  7709      781
3     3 North-Apulia      1     1      911          54     246  8113      549
4     4 North-Apulia      1     1      966          57     240  7952      619
5     5 North-Apulia      1     1     1051          67     259  7771      672
6     6 North-Apulia      1     1      911          49     268  7924      678
# ℹ 3 more variables: linolenic <dbl>, arachidic <dbl>, eicosenoic <dbl>

RStudio Projects

  • Help you keep track of the files for a data science project
  • File -> New Project -> New Directory
    • Name your new project something descriptive
    • Put the project in sensible folder
  • Move data into the project folder (into a data/ subdirectory if multiple files)
  • .R files in the project folder will find your data automatically without needing a file path.

Test Your Skills

  1. Navigate to https://www.ncdc.noaa.gov/cdo-web/search?datasetid=GHCND
  2. Select daily summaries
  3. Search for Zip codes
  4. Enter your Zip code (or 84321, Logan)
  5. Search
  6. Add a weather station to the cart
  7. Select Custom GHCN-Daily CSV as the output format
  8. Use the default range
  9. Custom options: Select all data types
  10. Submit the request and wait for the email. Download the resulting CSV file.
  11. Write code to read in the data.

Intro to Programming

Computers…

An old bald man with a moustach has an index finger raised, with text 'Malicious compliance is the best compliance'

Engineers…

If you ever code something that 'feels like a hack but it works' just remember that a CPU is literally a rock that we tricked into thinking - @Daisyowl tweet, 14 Mar 2017. Follow-up tweet: not to oversimplify, first you have to flatten the rock and put lightning inside it.

a word of caution: if the rock thinks too hard it will become hot enough to boil water

-(Jake Chanenson, 6/17/20)

Source

Alternately…

Computers are warm rocks we tricked into doing math and it’s a miracle they do anything.

Teaching Rocks to do Math

  • Remember you’re talking to a rock (“dumb as a box of rocks…”)
  • You have to know a concept really well before you start programming
  • Be extremely specific
  • Consider what assumptions you are making.
    • Try not to make them unless necessary.
    • If necessary, test to ensure they’re met.

Installation/Setup

Lab: Bread Programming