FES 720 Introduction to R

R Style Guide I: Syntax

Steve McQueen, your (R) style guru

=======

Coding styles help communication

Good coding style is like correct punctuation:

you can manage without it,

butitsuremakesthingseasiertoread.

======

Your code has 1 author; but many readers

you, tomorrow

you, on Friday

you, next week

you, next year

your friend

your friend’s friend

your mum

your reviewer

your third reviewer

your revising your manuscript

me

the dog

=======

There are many different styles of writing code

Try to develop a consistent style

=======

Consistent style is important, because …

=======

Style can be applied to:

  1. Syntax

  2. Files

  3. Functions

  4. Code documentation

========

Syntax Style

The arrangement of words and phrases

  1. Object names.

  2. Spacing.

  3. Argument names.

  4. Indenting.

  5. Long lines.

  6. Assignment.

  7. Semicolons.

  8. Quotes.

========

1. Object names

R is case-sensitive … other software (M$, …) is not.

Principles

Practice

=======

2. Spacing

Principle

Practice

Put a space:

=======

3. Argument names

Two kinds of arguments:

Principle

Practice

========

4. Indenting

Principle

Practice

=======

5. Long lines

Principle

Practice

=======

6. Assignment

Principle

Practice

x <- 1:10

# No, no, no, no, no, nooooooooooo ...
x = 1:10

=======

7. Semicolons

Principle

Practice

=======

8. Quotes

Principle

Practice

simonSays <- "Great work, folks!"

R help Quotes

=======

Links to various R style guides

Google: One of the first.

Hadley Wickham: Hadley WIckham built on Google’s guide …

Hadley’s Tidyverse … and eventually re-organised everything.

Microsoft A slightly different approach

Rchaeology of Style Learning R style by looking at the R source code

C S Gillespie R style and teaching

=======

Best Practice Lab: Style I: Syntax

Correct these R code snippets following the above style.

  1. average<-mean(feet/12+inches,na.rm=TRUE)

  2. x <- 1 : 10

  3. x[1,]

  4. mean(x = 1:10, , FALSE)

  5. mean(, TRUE, x = c(1:10, NA))

  6. do_something_very_complicated("that", requires, many, arguments, "some of which may be long" )

  7. x=5


Updated: 2017-09-14