01 / 21

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.

R Programming

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?

★ Fewer Bugs
Fix a bug once in one function instead of hunting through dozens of copy-pasted blocks.
★ Readability
Short, named functions make your script read almost like plain English.
★ Reusability
A well-written function can be used across projects with zero extra effort.

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.

WET Code
mean(df$col_a)
mean(df$col_b)
mean(df$col_c)
Same pattern ✕ 3 DRY Code
get_mean \( \leftarrow \) function(col)
mean(col)
lapply(df, get_mean)
One function, many uses

Anatomy of an R Function

calc_area \( \leftarrow \) function(width, height) {
area \( \leftarrow \) width * height
return(area)
}
Name Parameters Body Return Usage: calc_area (5, 10) # returns 50

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

1
Spot the pattern. Look for blocks of code that appear two or more times with only small differences.
2
Identify what varies. The differing pieces become your function's parameters.
3
Extract into a function. Wrap the shared logic in function(...) { } and give it a clear, descriptive name.
4
Replace every copy. Swap each duplicated block with a call to your new function.
5
Test. Run your script and confirm the output is identical to before.

The Refactoring Workflow

1. Spot Repetition Find duplicated blocks 2. Find Differences These become params 3. Write Function Extract shared logic 4. Replace Copies Call function instead 5. Test Output Same results? Done! Before:
\( \frac{\text{sd}(\text{df\$math})}{\sqrt{\text{length}(\text{df\$math})}} \)
\( \frac{\text{sd}(\text{df\$read})}{\sqrt{\text{length}(\text{df\$read})}} \)
After:
se \( \leftarrow \) function(x) \( \frac{\text{sd}(x)}{\sqrt{\text{length}(x)}} \)
se(df$math); se(df$read)

Example 1: Before Refactoring

Suppose you compute the z-score for three different columns. Each block is nearly identical:

# Column 1 z_math <- (df$math - mean(df$math)) / sd(df$math) # Column 2 z_read <- (df$read - mean(df$read)) / sd(df$read) # Column 3 z_sci <- (df$sci - mean(df$sci)) / sd(df$sci)

Example 1: After Refactoring

# Step 1: Extract the function zscore <- function(x) { (x - mean(x)) / sd(x) } # Step 2: Replace every copy z_math <- zscore(df$math) z_read <- zscore(df$read) z_sci <- zscore(df$sci)

Example 2: Repeated Plot Code

You create the same style of histogram for several variables:

hist(df$math, col="steelblue", main="Math Scores", xlab="Score") hist(df$read, col="steelblue", main="Reading Scores", xlab="Score") hist(df$sci, col="steelblue", main="Science Scores", xlab="Score")

Example 2: Refactored with a Function

plot_hist <- function(data, title) { hist(data, col = "steelblue", main = title, xlab = "Score") } plot_hist(df$math, "Math Scores") plot_hist(df$read, "Reading Scores") plot_hist(df$sci, "Science Scores")

Example 3: Default Parameters

R lets you set default values for parameters. Callers only supply them when they want something different:

summarize_col <- function(x, digits = 2) { c( mean = round(mean(x), digits), sd = round(sd(x), digits), median = round(median(x), digits) ) } summarize_col(df$math) # uses digits = 2 summarize_col(df$read, 4) # uses digits = 4

When Should You Refactor?

★ Rule of Three
If you copy-paste the same block three times, it is time to extract a function.
★ Bug Discovery
Found a bug in duplicated code? Refactor first, then fix the bug in one place.
★ Before Sharing
Before handing code to a teammate or teacher, clean it up so they can read it easily.

Common Mistakes

✕ Hardcoded Values
Leaving a specific number (like n = 30) inside the function instead of making it a parameter.
✕ Too Many Parameters
If a function needs 8+ arguments, it is probably doing too much. Split it into smaller functions.
✕ Vague Names
Naming a function 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

When you extract this into a function, what should the parameter represent?

Question 3 of 5

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

What is the best advice for this student?