Data Ethics & Best Practices
All Levels
5 hrs
2 Concepts
Your Learning Map
📌 You already know
You can write functions and full analyses.
🎯 You'll learn here
Writing professional, shareable code — a consistent style (
lintr) and documenting functions with roxygen2.🌍 Where it's used
Code that teammates (and future-you) can read and trust is what separates a script from a real project.
🔗 Unlocks next
These habits make the capstone and any package reviewable.
M1
Code Quality
Concept 1
Style Guide and lintr
Consistent style makes code maintainable. R uses tidyverse style: snake_case names, spaces around operators, 80-char line limit.
R
# styler auto-formats your code
library(styler); style_file('analysis.R')
# lintr checks style violations
library(lintr); lint('analysis.R')
# Good style:
mean_score <- mean(scores, na.rm = TRUE)
# Bad style:
meanScore<-mean(scores,na.rm=TRUE)
R — A clean, named function
LIVE READY
Output (verified)
[1] 22.7
Solved Examples
Example 1
Apply the concept of Style Guide and lintr to a sample dataset. Show at least two approaches.
# See the code example above and adapt it to your data. # Always check your output with str() and head().
Self-Assessment (2 questions)
Q1. The lintr package is used to:
lintr statically checks code against a style guide, flagging issues without running it.
Q2. The tidyverse style guide recommends naming objects with:
The tidyverse style guide recommends lowercase snake_case for object and function names.
M2
Documentation and Reproducibility
Concept 1
roxygen2 Function Documentation
Document functions with #' comments using roxygen2 syntax. Run devtools::document() to generate man pages.
R
#' Compute student grade
#' @param score Numeric score (0-100)
#' @return Character: 'A','B','C', or 'F'
#' @examples
#' get_grade(85) # 'B'
get_grade <- function(score){
dplyr::case_when(
score >= 90 ~ 'A',
score >= 80 ~ 'B',
score >= 65 ~ 'C',
TRUE ~ 'F'
)
}
Solved Examples
Example 1
Apply the concept of roxygen2 Function Documentation to a sample dataset. Show at least two approaches.
# See the code example above and adapt it to your data. # Always check your output with str() and head().
Self-Assessment (2 questions)
Q1. roxygen2 generates function documentation from:
roxygen2 turns #' comment tags (@param, @return) into .Rd help files.
Q2. Which roxygen2 tag documents a function argument?
@param name description documents an argument; @return documents the returned value.