Good practices in R
Tutorial on writing clean and readable cod
Tips and tricks for writing better code
Important
🏗 Under construction
Writing Clean and Readable Code
Example in R:
# Good: Use meaningful variable names and comments
<- 1000 # Number of individuals in the population
population_size <- 100 # Number of individuals in the sample
sample_size
# Avoid: Using unclear or abbreviated variable names
<- 1000
ps <- 100 ss
Using Comments and Documentation
# Good: Add comments to explain complex operations or logic
<- function(data) {
calculate_mean # Calculate the sum of elements in the data
<- sum(data)
total
# Calculate the mean by dividing the total by the number of elements
<- total / length(data)
mean_value
return(mean_value)
}
# Avoid: Lack of comments and explanation
<- function(d) {
calc_mean <- sum(d)
t <- t / length(d)
m return(m)
}
Avoiding Global Variables and Code Dependencies
# Good: Use local variables within functions to avoid global scope pollution
<- function(data) {
calculate_variance <- length(data)
n <- sum(data) / n
mean_value
# Calculate the variance using local variables
<- sum((data - mean_value)^2) / (n - 1)
variance
return(variance)
}
# Avoid: Using global variables in functions
<- 0
mean_value <- function(data) {
calc_variance <- length(data)
n <<- sum(data) / n
mean_value
# Calculate the variance using global variables
<- sum((data - mean_value)^2) / (n - 1)
variance
return(variance)
}