Basics and Syntax
In RStudio, auto-format your code with with the Styler Addin:
Technique and Structure
1:1 generates a sequence of length one,
1:0 generates a sequence of length two,
[1, 0]. Therefore, when an object
x with zero rows is passed into
for (i in 1:nrow(x)), the code in the for loop will be executed twice, which is probably very different from what you expect. Therefore always use
seq_along() in place of
: ranges in your
for loops. E.g.,
for (i in seq_len(nrow(x))). Reference.
Trying to learn R reminds me of when I, as an undergraduate math-philosophy double major, had to take a logic class in the philosophy department. In the math department, the class could have been compressed into two weeks. But in the philosophy department, even spread out over three months, it was the subject of much frustration for the less mathematically inclined philosophy students.
Similarly, most resources for learning R are directed at non-programmers, and as such are painfully gentle. So I will be maintaining here a list of satisfyingly terse explainers and tutorials.