Refactoring in R
Functions from Repeated Code
Learn to identify duplicated code, extract it into reusable functions, and write R programs that are cleaner, shorter, and easier to debug.
What is Refactoring?
Refactoring means restructuring existing code without changing what it does. The output stays the same: your program still produces the same results. But the internal structure becomes cleaner, more readable, and easier to maintain.
Why Does Refactoring Matter?
The DRY Principle
DRY stands for "Don't Repeat Yourself." It is the single most important rule behind refactoring. Every piece of knowledge or logic should exist in exactly one place in your codebase.
Anatomy of an R Function
Functions vs Copy-Paste
| Function | Copy-Paste | |
|---|---|---|
| Bug Fix | Fix once | Fix everywhere |
| Readability | Descriptive name | Wall of code |
| Testing | Test one function | Test every copy |
| Line Count | Shorter | Longer |
| Change a Parameter | Update one signature | Hunt and replace |
How to Refactor: Step by Step
function(...) { } and give it a clear, descriptive name.The Refactoring Workflow
Example 1: Before Refactoring
Suppose you compute the z-score for three different columns. Each block is nearly identical:
Example 1: After Refactoring
Example 2: Repeated Plot Code
You create the same style of histogram for several variables:
Example 2: Refactored with a Function
Example 3: Default Parameters
R lets you set default values for parameters. Callers only supply them when they want something different:
When Should You Refactor?
Common Mistakes
n = 30) inside the function instead of making it a parameter.do_stuff() tells the reader nothing. Use descriptive names like calc_zscore().Summary: Refactoring Checklist
| Step | Action | Result |
|---|---|---|
| 1. Identify | Find repeated code blocks | Know what to refactor |
| 2. Parameterize | Mark what varies | Function parameters |
| 3. Extract | Write the function | Single source of truth |
| 4. Replace | Swap copies with calls | Shorter, cleaner script |
| 5. Test | Run and compare output | Same results, better code |
Question 1 of 5
What does the DRY principle stand for?
Question 2 of 5
You have this repeated code in your R script:
mean(df$a) / sd(df$a)
mean(df$b) / sd(df$b)
mean(df$c) / sd(df$c)
When you extract this into a function, what should the parameter represent?
df$a, df$b, df$c). That varying piece becomes the parameter.Question 3 of 5
Consider this R function:
What does rescale(c(2, 4, 6)) return?
Question 4 of 5
Which of the following is a common mistake when writing R functions?
Question 5 of 5
A student writes:
calc <- function(a, b, c, d, e, f, g, h) { ... }
What is the best advice for this student?