Writing code for humans, not just for computers
Write programs for people, not computers
Wilson et al. (2014) PLoS Biol 12:e1001745
Break large tasks into small units.
If you write the same code more than once, make it a function.
If a line/block of code is complicated, make it a function.
Modularity is really important for readability.
No long streams of code; rather, a short set of function calls.
1000
max_iter <- 1000tol_convergence <- 0.0001👎 Don’t
👍 Do
ggplot(mtcars, aes(x = disp, y = mpg, color = factor(cyl))) +
geom_point(alpha = 0.5, size = 2)+
geom_smooth(method = "lm", se = FALSE)+
labs(title = "Engine Displacement and MPG",
subtitle = "The bigger the car the less fuel efficient",
x = "Engine displacement (size of engine)",
y = "Miles-per-Gallon")Break them into multiple lines
👎 Don’t
tmp1, tmp2, ...i, j, x, y in the simplest situationsfv, what might it do?nms, what could it be?g, g2, and gg, it’ll need a lot of comments.markers vs mnamescamelCase vs snake_case vs CapitalCasenind vs n.vartotal and totalsn.cluster and n.clustersresult and resultsMat and matg and ggSome things are tricky and deserve explanation, so that when you come back to it, you have a guide.
But in many cases, code can be rewritten to be clear and self-documenting.
Commenting takes time. And no one ever goes back and adds comments later. It’s another one of those “invest for the future” type of things.
error("nrow(X) != nrow(Y)")"You need to first run calc.genoprob().""nrow(X) (", nrX, ") != nrow(Y) (", nrY, ")"X'X is singular
Comments