Modifying data with the dplyr package

The following makes use of the dplyr package. You may need to install it from CRAN using the code install.packages("dplyr") if you want to run this on your computer. (The package is already installed on the notebook container, however.)

library(dplyr)
Attaching package: 'dplyr'

The following objects are masked from 'package:stats':

    filter, lag

The following objects are masked from 'package:base':

    intersect, setdiff, setequal, union
UK <- data.frame(
           Population = c(55619400,1885400,5424800,3125000),
           Area = c(50301,5460,30090,8023),
           GVA = c(28096,20000,24800,19900),
           country = c("England",
                         "Northern Ireland",
                         "Scotland",
                         "Wales"))
UK %>% mutate(Density = Population/Area)
  Population  Area   GVA          country   Density
1   55619400 50301 28096          England 1105.7315
2    1885400  5460 20000 Northern Ireland  345.3114
3    5424800 30090 24800         Scotland  180.2858
4    3125000  8023 19900            Wales  389.5052

Equivalent code using ‘base’ R:

within(UK, Density <- Population/Area)
  Population  Area   GVA          country   Density
1   55619400 50301 28096          England 1105.7315
2    1885400  5460 20000 Northern Ireland  345.3114
3    5424800 30090 24800         Scotland  180.2858
4    3125000  8023 19900            Wales  389.5052