Best Coding Practices

RaukR 2025 • R Beyond the Basics

Styling and conventions for neat and tidy code.
Author

Marcin Kierczak, Sebastian DiLorenzo

Published

09-Jun-2025

Note

The objective of this lab is to improve your coding skills by focusing on coding style, code benchmarking and optimization. Below, you will find a number of tasks connected to the topics covered in the Best Coding Practices lecture. Some tasks extend lectures content and require you to find some more information online. Please, note that while we are providing example solutions to many tasks, these are only examples. If you solve a task in a different way it does not matter your solution is wrong. In fact, it may be better than our solution. If in doubt, ask a TA for help. We are here for you!

1 Coding Style

1.1 Task: Valid Variable Names.

Which of the following are valid/good variable names in R. What is wrong with the ones that are invalid/bad?

  • var1
  • 3way_handshake
  • .password
  • __test__
  • my-matrix-M
  • three.dimensional.array
  • 3D.distance
  • .2objects
  • wz3gei92
  • next
  • P
  • Q
  • R
  • S
  • T
  • X
  • is.larger?

1.2 Task: Obscure Code.

The code below works, but the style can be improved. Improve it!

myIterAtoR.max <- 5
second_iterator.max<-7
col.NUM= 10
row.cnt =10
fwzy45 <- matrix(rep(1, col.NUM*row.cnt),nrow=row.cnt)
for(haystack in (2-1):col.NUM){
  for(needle in 1:row.cnt) {
if(haystack>=myIterAtoR.max){
fwzy45[haystack, needle]<-NA}
}}
iter_max <- 5
col_num <- 10
row_num <- 10
A <- matrix(rep(1, col_num * row_num), nrow = row_num)
for (i in 1:col_num) {
  for (j in 1:row_num) {
    if (i >= iter_max) {
      A[i, j] <- NA
    }
  }
}

# Can you improve the code more by eliminating loops or at least one of them?

1.3 Task: Better Formatting.

Improve formatting and style of the following code:

simulate_genotype <- function( q, N=100 ) {
  if( length(q)==1 ){
    p <- (1 - q)
    f_gt <- c(p^2, 2*p*q, q^2) # AA, AB, BB
  }else{
    f_gt<-q
  }
  tmp <- sample( c('AA','AB','BB'), size =N, prob=f_gt, replace=T )
  return(tmp)
}
simulate_genotype <- function(q, N = 100) {
  if (length(q) == 1) {
    p <- (1 - q)
    f_gt <- c(p^2, (2 * p * q), q^2) # AA, AB, BB
  } else {
    f_gt <- q
  }
  result <- sample(c('AA', 'AB', 'BB'), 
         size = N, 
         prob = f_gt, 
         replace = TRUE)
  return(result)
}

1.4 Task: Hidden Variable.

Assign a vector of three last months (abbreviated in English) in a year to a hidden variable my_months.

# If we do not know the length of the vector
.my_months <- rev(rev(month.abb)[1:3])

# or
.my_months <- month.abb[(length(month.abb)-2):length(month.abb)]

1.5 Bonus task: using air.

The example solutions for tasks 1.2 and 1.3 were written before the R package air was released. The package provides a set of functions that can help you with formatting code. Try to use air to reformat the code given in tasks 1.2 and 1.3 and compare with the example solutions. Are they similar? What did air not do?

1.6 Bonus task: Using options.

Use options to change the default prompt in R to hello :-) >.

Tip

Check what options are stored in the hidden variable called Options.

options(prompt = "hello :-) > ")
.Options
options(prompt = "> ") # restoring the default

2 Session

Click here
sessionInfo()
R version 4.4.3 (2025-02-28)
Platform: aarch64-apple-darwin20
Running under: macOS Sequoia 15.5

Matrix products: default
BLAS:   /Library/Frameworks/R.framework/Versions/4.4-arm64/Resources/lib/libRblas.0.dylib 
LAPACK: /Library/Frameworks/R.framework/Versions/4.4-arm64/Resources/lib/libRlapack.dylib;  LAPACK version 3.12.0

locale:
[1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8

time zone: Europe/Stockholm
tzcode source: internal

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

other attached packages:
[1] bsplus_0.1.5

loaded via a namespace (and not attached):
 [1] digest_0.6.37     lubridate_1.9.4   fastmap_1.2.0     xfun_0.52        
 [5] magrittr_2.0.3    knitr_1.50        htmltools_0.5.8.1 timechange_0.3.0 
 [9] rmarkdown_2.29    generics_0.1.4    cli_3.6.5         compiler_4.4.3   
[13] tools_4.4.3       evaluate_1.0.3    yaml_2.3.10       rlang_1.1.6      
[17] jsonlite_2.0.0    htmlwidgets_1.6.4