Character alignment (coding tip)

This post introduces a coding tip rather than an R function. Generally I recommend making an effort to align assignment characters in an R script, very roughly in blocks of 3-10 lines. Code written with aligned assignment characters is often much easier to read than code without alignment. This tip is generalizable to other programming languages.

Example. Below I’ve listed some code from the merge and format posts. However, in the top sets of code, I haven’t aligned the assignment characters. Notice that in the second set of the code, it is easier to quickly review variables and values.
> id1 <- c(2, 3, 4, 5, 7)
> heights <- c(62, 65, 71, 71, 67)
> d1 <- data.frame(id=id1, heights)
> 
> id2 <- c(1, 2, 6, 7, 8, 9, 10)
> weights <- c(147, 113, 168, 135, 144, 173, 128)
> d2 <- data.frame(id=id2, weights)
> 
> beta <- c(2.1, 6.21, 4.321, 5.4321)
> SE <- c(5, 1.49, 11.13, 0.31)
> t <- beta/SE
> 
> 
> 
> 
> id1     <- c(2, 3, 4, 5, 7)
> heights <- c(62, 65, 71, 71, 67)
> d1      <- data.frame(id=id1, heights)
> 
> id2     <- c(1, 2, 6, 7, 8, 9, 10)
> weights <- c(147, 113, 168, 135, 144, 173, 128)
> d2      <- data.frame(id=id2, weights)
> 
> beta <- c(2.1, 6.21, 4.321, 5.4321)
> SE   <- c(5, 1.49, 11.13, 0.31)
> t    <- beta/SE
Aligning assignment characters makes it easier for others to read your code, which is an important and marketable skill.
Thank you. Thanks to Chris Barr, who first told me about this coding technique.

Leave a Reply