Coding style (and code commenting) will become increasingly more important as we get into more advanced and involved programming tasks
- A few R "style guides" exist:
Borrowing Hadley Wickham's words: > You don’t have to use my style, but you really should use a consistent style.
R style recommendations
Enforced style: Assignment operator
Assignment operator. USE <-
student.names <- c("Eric", "Hao", "Jennifer") # Good
student.names = c("Eric", "Hao", "Jennifer") # Bad
- Note: When specifying function arguments, only
=
is valid
sort(tv.hours, decreasing=TRUE) # Good
sort(tv.hours, decreasing<-TRUE) # Bad!!
Enforced style: Spacing
Binary operators should have spaces around them
Commas should have a space after, but not before (just like in writing)
3 * 4 # Good
3*4 # Bad
which(student.names == "Eric") # Good
which(student.names=="Eric") # Bad
- For specifying arguments, spacing around
=
is optional
sort(tv.hours, decreasing=TRUE) # Accepted
sort(tv.hours, decreasing = FALSE) # Accepted
Enforced style: Variable names
To make code easy to read, debug, and maintain, you should use concise but descriptive variable names
Terms in variable names should be separated by _
or .
# Accepted
day_one day.one day_1 day.1 day1
# Bad
d1 DayOne dayone
# Can be made more concise:
first.day.of.the.month
- Avoid using variable names that are already pre-defined in R
# EXTREMELY bad:
c T pi sum mean