3
Week 6, Part 3
jj1088@georgetown.edu
DSAN Summer Bootcamp 2024
Georgetown University
Indices
Start from 0
+!If you’re used to Python, + feels like a natural way to combine things
R forces you to think explicitly about combining (\(\neq\) adding): more restrictive +
For strings:
For numeric lists…
One key reason: tidyverse built on the pipe operator |>
Recognition that data science often involves pipelines: chains of operations performed in sequence
Base R approach:
Tidyverse approach:
Now imagine pipelines used by giant companies, e.g., training Netflix’s recommendation engine!
|>: Good News and Bad Newsf() |> g() just means: take the result of the call f() and pass it as the first argument to g()|> is intuitively “backwards compatible” with many base R functions[Quick Note:]
%>% operator from tidyverse|>!%>% to |> for instant efficiency boost 😎Earlier we saw how R doesn’t allow "Hi" + " " + "Jeff"…
So how do we combine strings?
paste() and paste0()!
range() \(\leftrightarrow\) R seq()
paste0() with Vectors!Rarely used, despite greater similarity to Python lists 😵💫
Key difference: all elements of a vector must have same type; elements of a list may have different types
(Note how each element is a vector: character vector, integer vector, and boolean vector)
| Col A | Col B | |
|---|---|---|
| Row 1 | Val 1A | Val 1B |
| Row 2 | Val 2A | Val 2B |
DataFrame \(\leftrightarrow\) R data.frame Given a .csv with missing entries:
Python defaults to object columns with NaN (Not-a-Number) values
Intuitive fix usually isn’t what you want:
id name email
0 0 jeff jeff@jeff.com
1 1 nan nobody@no.com
2 3 zayd z@email.biz
'nan'
This alternative approach ensures missing values are empty strings
R reads missing values in character columns as empty strings by default
…And also has a built-in NA value!
my_data_2.csv
For data analysis (cleaning, plotting), data.frame is usually the way to go
For linear algebra (inverting, multiplying matrices)…
Use 2D vectors!
In Base R, filtering involves two steps:
Create a boolean expression that will evaluate to TRUE for the rows/columns you want to keep, and FALSE otherwise
Use it in the correct “slot” of R’s access operator []:
R will go through each row, evaluate <row filter>, and keep the row if and only if <row filter> evaluates to TRUE
Example: Selecting only rows with odd-numbered id values:
Create a vector with names of columns you want to keep:
Use as the sole argument to R’s access operator []:
Example: Keeping just the name and fav_num columns:
sample() function, but be careful! It does not work directly on data.frame objects 😱 Instead:2024 DSAN Bootcamp W06-3: Intro to R