Skip to Content
Course content

98: Common R Interview Questions on Vectorization

Click on the "Edit" button in the top corner of the screen to edit your slide content.

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_risk without using any for loops or if statements.
  • 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) and income <- c(60000, 40000, 30000, 20000).
  • Verify that the output matches the logic of the original function.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.