Introduction to R and Rstudio

Session - objects

Zoë Turner

Creating an object

Objects that are created from imported data appear in the Environment pane

It is possible to also create objects from code

Temporary and temporary

The following code exists only as the code is run and the underlying object beds_data is never changed

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))
# A tibble: 255 × 4
   org_name                                  total_beds total_occupancy perc_occ
   <chr>                                          <dbl>           <dbl>    <dbl>
 1 Barnet, Enfield And Haringey Mental Heal…      10403           10214    0.982
 2 Bradford District Care Trust                     598             581    0.972
 3 Hertfordshire Partnership University            3856            3676    0.953
 4 Camden And Islington                            3718            3540    0.952
 5 Devon Partnership                               5922            5595    0.945
 6 North Essex Partnership University              5079            4790    0.943
 7 Sussex Partnership                             12331           11607    0.941
 8 Essex Partnership University                    3855            3627    0.941
 9 Manchester Mental Health And Social Care…       3487            3278    0.940
10 Birmingham And Solihull Mental Health          14560           13572    0.932
# ℹ 245 more rows

Saving as an object

In R the assign operator <- is conventionally used instead of = although that will work

Shortcut key is Alt and -

bed_occupancy <- 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))

Naming style

The way names are written out is a question of style but it’s best to be consistent.

Other ways of writing names will work but are best avoided like ALLCAPS and With Spaces

camelCase # first letter is small case

PascalCase # every letter is capital

snake_case # lower case and words are separated with underline

kebab-case # lower case and hyphen, used in RMarkdown but not R scripts

End session