1.2 Data

(and programming)

Perception of Data Science & Statistics

As you come in
Answer Questions 1-3 in Survey 1.2.p Introduction to Data Science on Canvas

5 minutes: Form a group of 3-4 people and answer questions 4-5

Why R?

There are only two kinds of languages: the ones people complain about and the ones nobody uses.

– Bjarne Stroustrup (creator of the C++ programming language)

What is R?

  • An open-source clone of S, which was a programming language developed at the Bell Telephone Laboratories in 1976.
  • A language built for working with data

A skeleton army with text 'Rule 6 of the pirate code: What's a pirate's favorite letter?'

Pros and Cons

Pros:

Cons

  • Optimizes programmer time - computing time can be slower
    • Industry uses R for prototyping, Python/C for production
  • Easy to write bad/hard-to-maintain code
    This is true in almost every language
  • Different conventions than C/Python/Java
    Counting from 1, 2, 3, … rather than 0, 1, 2, …

Why Not Spreadsheets?

  1. Reproducibility. Code is like a recipe, Spreadsheets are one-off analyses. Things get changed accidentally.
  2. Spreadsheet references are less readable than variable names
  3. It’s best to separate data, code, and output. Spreadsheets mix them.
  4. Spreadsheet functionality is limited compared to add-on libraries
  5. Excel charts are terrible (personal opinion)

Additional Spreadsheet Tales

One in five genetics papers contains errors thanks to Microsoft Excel

Eight Famous Excel Errors That Cost Millions (And One That Renamed Human Genes)

Spreadsheet error masked $6 billion dollar JP Morgan Loss (2012)

Spreadsheet errors can have disastrous consequences – yet we keep making the same mistakes

SpreadsheetBench tasks for AI agents - scores of 34.89% (as of 08-2026) on v2 task

Attendance Code

Go to Canvas and fill in the attendance code for today

Two pink fuzzy monsters approach a doorway. One monster hass glasses, the other has heart eyes and a rainbow 'mind blown' cloud bursting from its head. Glitter and butterflies are coming from the door, and a blue Twitter bird with an R on it is sitting above the door. There is a welcome mat in front. Inside the door, hashtags like #rstats, #RLadies, and #datavis are shown, as well as @OneRTipADay, @rOpenSci, @R-Bloggers, @WeAreRLadies, @hadley are featured in a landscape with rainbows, butterflies, flowers, and sunshine.

Artwork by Allison Horst, CC-BY 4.0

Importing Data into R

Getting Started

  1. Open RStudio
  2. Open an Editor window (by default, a text file in the top left corner)

Setting Up

library(readr)
library(dslabs)

path <- system.file("extdata", package="dslabs")

files <- list.files(path)
files
1
Read in files efficiently
2
Package to go with the IDS books
3
Find the folder with external data files (extdata) in the dslabs package
4
What files are in the extdata folder?
 [1] "2010_bigfive_regents.xls"                               
 [2] "calificaciones.csv"                                     
 [3] "carbon_emissions.csv"                                   
 [4] "fertility-two-countries-example.csv"                    
 [5] "HRlist2.txt"                                            
 [6] "life-expectancy-and-fertility-two-countries-example.csv"
 [7] "murders.csv"                                            
 [8] "olive.csv"                                              
 [9] "RD-Mortality-Report_2015-18-180531.pdf"                 
[10] "ssa-death-probability.csv"                              

Setting Up

files <- list.files(path, full.names = T)
files
1
List the files AND the path where the files are located
 [1] "/home/susan/R/x86_64-pc-linux-gnu-library/4.5/dslabs/extdata/2010_bigfive_regents.xls"                               
 [2] "/home/susan/R/x86_64-pc-linux-gnu-library/4.5/dslabs/extdata/calificaciones.csv"                                     
 [3] "/home/susan/R/x86_64-pc-linux-gnu-library/4.5/dslabs/extdata/carbon_emissions.csv"                                   
 [4] "/home/susan/R/x86_64-pc-linux-gnu-library/4.5/dslabs/extdata/fertility-two-countries-example.csv"                    
 [5] "/home/susan/R/x86_64-pc-linux-gnu-library/4.5/dslabs/extdata/HRlist2.txt"                                            
 [6] "/home/susan/R/x86_64-pc-linux-gnu-library/4.5/dslabs/extdata/life-expectancy-and-fertility-two-countries-example.csv"
 [7] "/home/susan/R/x86_64-pc-linux-gnu-library/4.5/dslabs/extdata/murders.csv"                                            
 [8] "/home/susan/R/x86_64-pc-linux-gnu-library/4.5/dslabs/extdata/olive.csv"                                              
 [9] "/home/susan/R/x86_64-pc-linux-gnu-library/4.5/dslabs/extdata/RD-Mortality-Report_2015-18-180531.pdf"                 
[10] "/home/susan/R/x86_64-pc-linux-gnu-library/4.5/dslabs/extdata/ssa-death-probability.csv"                              

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.

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.