Debugging in R: Identify and Fix

Instruction: Identify why the following R code fails, then fix it to assign one label per row. Label missing x as "unknown". Explain how the answer would differ if a single decision for the whole data frame were intended.

Context: This question assesses the candidate's ability to effectively debug R code, showcasing their problem-solving skills and attention to detail.
df <- data.frame(x = c(1, -1, NA_real_))
if (df$x > 0) {
  df$label <- "positive"
} else {
  df$label <- "nonpositive"
}

Updated

Official answer available

Read the opening below, then unlock the full answer and practical guidance.

if requires one nonmissing logical value, but df$x > 0 produces a vector. In this example the condition therefore fails when it contains several elements. For a rowwise label, use a vectorized operation and an explicit missing-value policy.

df <- data.frame(x = c(1, -1, NA_real_)) df$label <- ifelse(is.na(df$x), "unknown", ifelse(df$x...

Related Questions