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
98: Common R Interview Questions on Vectorization
If you're heading into an R interview, there is one specific trap that almost every junior to mid-level dev falls into. It usually happens when they're asked to implement a conditional transformation on a dataset. I've seen brilliant engineers freeze up because they tried to apply a standard if statement to a vector and R started screaming at them with warnings.
Take a look at this snippet. Imagine you're writing a function to categorize customer spending levels:
calculate_tier <- function(spend) {
if (spend > 1000) {
return("Gold")
} else {
return("Silver")
}
}
customer_spend <- c(500, 1200, 800, 1500)
tiers <- calculate_tier(customer_spend)
# Warning message: the condition has length > 1 and only the first element will be used
# [1] "Silver"
The "Condition Has Length > 1" Warning
Here is what's happening: the if statement in R is not vectorized. It expects a single TRUE or FALSE. When you pass it the customer_spend vector, R doesn't say, "Oh, I should do this for every element." Instead, it looks at the first element (500), sees it's not greater than 1000, returns "Silver", and then throws a warning telling you that it ignored the rest of the vector.
In an interview, if you write this, the interviewer isn't just looking at the bug; they're checking to see if you understand the fundamental philosophy of R. R is designed to operate on vectors. If you're writing a loop or a scalar if to process data, you're fighting the language.
Switching to Element-wise Logic
To fix this, we need a function that handles vectors natively. The most common answer is ifelse(), but there are more performant ways to do it depending on the scale of your data.
# The quick fix: ifelse()
calculate_tier_vec <- function(spend) {
ifelse(spend > 1000, "Gold", "Silver")
}
tiers <- calculate_tier_vec(customer_spend)
# [1] "Silver" "Gold" "Silver" "Gold"
This works because ifelse() is specifically designed to iterate over the vector internally (in C), which is orders of magnitude faster than a for loop in R. If you want to impress an interviewer, you can also mention logical indexing, which is often even faster for simple assignments:
tiers <- rep("Silver", length(customer_spend))
tiers[customer_spend > 1000] <- "Gold"
Explaining the Performance Gap to an Interviewer
When an interviewer asks, "Why is vectorization better than a loop?", don't just say "it's faster." That's the generic answer. Give them the engineering answer.
Tell them that R is an interpreted language. Every time a for loop iterates, R has to check the type of the variable, look up the function, and manage the environment. This is called "overhead." Vectorized functions, however, call compiled C or Fortran code. They perform the operation on the entire block of memory at once. You're essentially shifting the loop from the slow R layer to the fast compiled layer.
I always suggest mentioning that while vectorization is the gold standard, it can occasionally lead to massive memory spikes if you create too many intermediate large vectors. It's a trade-off: you're trading memory (space) for speed (time). Showing you understand that nuance is what separates a coder from a software engineer.
📋 Practical Task
Optimizing a Loan Risk Scoring System
You have been given a legacy function that calculates a risk score for loan applicants. Currently, it uses a for loop and if/else blocks, making it incredibly slow for datasets with millions of rows. Your task is to rewrite this function to be fully vectorized.
The Legacy Code:
calculate_risk <- function(credit_score, income) {
scores <- numeric(length(credit_score))
for (i in 1:length(credit_score)) {
if (credit_score[i] > 700 && income[i] > 50000) {
scores[i] <- 1 # Low Risk
} else if (credit_score[i] > 600 || income[i] > 80000) {
scores[i] <- 2 # Medium Risk
} else {
scores[i] <- 3 # High Risk
}
}
return(scores)
}
Requirements:
- Rewrite
calculate_riskwithout using anyforloops orifstatements. - Use
ifelse()or logical indexing to handle the three risk tiers. - Test your function with the following vectors:
credit_score <- c(750, 650, 500, 800)andincome <- c(60000, 40000, 30000, 20000). - Verify that the output matches the logic of the original function.
There are no comments for now.