Introduction to R and Rstudio

Session - styling code

Zoë Turner

Code style

An updated version of R4DS now includes a section on code style

It particularly mentions the package {styler} which, when run becomes an addin to RStudio, and automatically applies the tidyverse style to code

install.packages("styler")

Indentation

RStudio also automatically indents according to the function bracket positions

Highlighting line of code using the keyboard shortcut Ctrl+i applies indents

Have a go - look at automatic indentation

  • beds_data then press return, where does the cursor go?
  • beds_data |> then return, where does the cursor go now?
  • beds_data |> select(org_name, org_code) and put the select on a new line, then put org_code onto a new line.
  • Copy the following to the Editor and indent using Ctrl+i:
beds_data |> 
select(org_code,
everything)
08:00

Space code

Using spaces helps with readability

The code below will run as R doesn’t need spaces to work:

beds_dataset=beds_data|>summarise(total_beds=sum(beds_av,na.rm=TRUE),total_occupancy=sum(occ_av,na.rm=TRUE),.by=org_name)|>mutate(perc_occ=total_occupancy/total_beds)|>arrange(desc(perc_occ))

Putting the spaces in can be effort after it’s been written

Have a go - {styler}

Firstly copy the code without spaces to the document

beds_dataset=beds_data|>summarise(total_beds=sum(beds_av,na.rm=TRUE),total_occupancy=sum(occ_av,na.rm=TRUE),.by=org_name)|>mutate(perc_occ=total_occupancy/total_beds)|>arrange(desc(perc_occ))

With {styler} loaded library(styler) go to the Add in drop down menu and select Style Active File

05:00

End session