R
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Data Structures
-
Section 4: Data Manipulation
-
Section 5: Visualization and Statistics
-
Section 6: Advanced R
-
Section 7: Practical Projects
-
Section 8: Interview Practice
-
Section 9: More Practice Exercises
-
Section 10: Shiny Apps in Depth
-
Section 11: More Data Wrangling
-
Section 12: Tidyverse Deep Dive
-
Section 13: Statistical Modeling Deep Dive
-
Section 14: Machine Learning in R
-
Section 15: R Visualization Deep Dive
-
Section 16: R Package Development Deep Dive
-
Section 17: R for Reproducible Research
-
Section 18: R and Databases
-
Section 19: R Performance Optimization
-
Section 20: Bioinformatics and Specialized R
-
Section 21: More Shiny Practice
-
Section 22: More Practice Exercises
-
Section 23: R Data Structures Deep Dive
-
Section 24: More Interview and Review
-
Section 25: R for Business Analytics
-
Section 26: R Text Mining and NLP
-
Section 27: R Spatial Data Analysis
-
Section 28: R Deep Learning
-
Section 29: Advanced Statistical Techniques
-
Section 30: R Object Systems Deep Dive
-
Section 31: R Environments and Metaprogramming
-
Section 32: R for Finance
-
Section 33: R for Clinical and Health Data
-
Section 34: More Shiny Advanced Practice
-
Section 35: R Data Cleaning Deep Dive
-
Section 36: R Reporting Automation
-
Section 37: More Practical Projects Round 2
-
Section 38: R Ecosystem and Career
-
Section 39: More Visualization Practice
-
Section 40: R for Experimentation
-
Section 41: R for Genomics and Bioinformatics Deep Dive
-
Section 42: R for Marketing Analytics
-
Section 43: R Data Import/Export Deep Dive
-
Section 44: R String Processing Deep Dive
-
Section 45: R for Actuarial and Insurance Analytics
-
Section 46: R Testing and Quality Assurance Deep Dive
-
Section 47: R Version Control and Collaboration
-
Section 48: R Advanced Functional Programming
-
Section 49: R for Supply Chain and Operations
-
Section 50: More Practice Exercises Round 3
-
Section 51: R Dashboards and BI Integration
-
Section 52: R Data Governance and Ethics
-
Section 53: More Modeling Practice
-
Section 54: R Final Capstone Projects
-
Section 55: R for Sports Analytics
-
Section 56: More Interview Practice Round 2
-
Section 57: R Networking and APIs
-
Section 58: R for Environmental Science
-
Section 59: R Notebook and Documentation Practices
-
Section 60: More Data Wrangling Mastery
-
Section 61: R for A/B Testing at Scale
-
Section 62: R Package Ecosystem Deep Dive
19: Working with Strings via stringr
I've seen this happen to almost every R developer I've mentored. You're cleaning a dataset, you need to filter some strings, and you reach for base R's grep(). It feels straightforward until you realize you've spent the last twenty minutes fighting with the return types.
# The goal: Get a list of logs that are "Critical" or "Error"
logs <- c("INFO: System start", "ERROR: Disk full", "DEBUG: Heartbeat", "CRITICAL: CPU Overheat")
# I want the actual strings, so I do this:
critical_logs <- grep("CRITICAL|ERROR", logs)
print(critical_logs)
# [1] 2 4
# Wait... why did I get numbers instead of the text?
The index vs. logical confusion
The problem here is that base R's string functions are inconsistent. grep() returns the indices of the matches. If you wanted the actual strings, you'd have to wrap that in a subsetting bracket: logs[grep(...)]. But then you realize grepl() (with an 'l') exists, which returns a logical vector (TRUE/FALSE). It's a constant mental tax: "Do I need the index, the logical, or the string itself?"
This is exactly why I stopped using base R for string manipulation and switched to stringr. It's a wrapper around the ICU library, but more importantly, it's designed for humans. Every function starts with str_, and the arguments are always in the same order: the string you're searching comes first, and the pattern comes second.
library(stringr)
# Now, if I want the actual strings, I use str_subset
critical_logs <- str_subset(logs, "CRITICAL|ERROR")
print(critical_logs)
# [1] "ERROR: Disk full" "CRITICAL: CPU Overheat"
# If I want a TRUE/FALSE vector for filtering a dataframe, I use str_detect
is_critical <- str_detect(logs, "CRITICAL|ERROR")
# [1] FALSE TRUE FALSE TRUE
Trimming the fat and swapping text
Real-world data is almost always filthy. You'll often find trailing spaces or inconsistent prefixes that make your joins fail. In base R, you'd be juggling gsub() and trimws(). In stringr, we have a much more intuitive pipeline.
Take a look at this messy vector of product IDs. They have random whitespace and a "PROD_" prefix we don't need:
ids <- c(" PROD_123 ", "PROD_456 ", " PROD_789")
# First, let's get rid of that annoying surrounding whitespace
ids <- str_trim(ids)
# Now, let's remove the prefix.
# Note: str_replace only does the first match; str_replace_all does every instance.
clean_ids <- str_remove(ids, "PROD_")
print(clean_ids)
# [1] "123" "456" "789"
Extracting specific patterns
Sometimes you don't want to remove text; you want to pull a specific piece out of a larger string. This is where str_extract() becomes your best friend. Instead of trying to figure out regexpr() and regmatches() (which are, frankly, a nightmare to type), you just tell stringr what you're looking for.
Imagine you have a column of emails and you just need the domain names. You can use a simple regular expression to grab everything after the @ symbol:
emails <- c("alice@gmail.com", "bob@yahoo.com", "charlie@outlook.com")
# Extract everything from the '@' to the end of the string
domains <- str_extract(emails, "@.*$")
print(domains)
# [1] "@gmail.com" "@yahoo.com" "@outlook.com"
I should mention: stringr is part of the tidyverse, so it plays incredibly well with dplyr. You can drop str_detect or str_replace directly into a filter() or mutate() call, and it just works. No more weird index-subsetting gymnastics.
📋 Practical Task
Standardizing Messy Inventory SKUs
You have been handed a vector of SKU codes from a legacy warehouse system. They are incredibly inconsistent: some have leading/trailing spaces, some are uppercase, some are lowercase, and some have an annoying "SKU-" prefix that needs to be removed for the new database.
Your task: Use the stringr package to clean the following vector: raw_skus <- c(" SKU-101a ", "sku-202B", " SKU-303C ", "sku-404d ")
The final result should be a vector where:
- All leading and trailing whitespace is removed.
- The "SKU-" or "sku-" prefix is gone.
- All characters are converted to uppercase.
Write the code to transform raw_skus into the cleaned version: c("101A", "202B", "303C", "404D").
There are no comments for now.