1.2 Solutions
1.2.1 Exercise 3
Calculate the square root of 1369 using the sqrt()
function.
sqrt(1369)
[1] 37
1.2.2 Exercise 4
Square the number 13 using the ^
operator.
13^2
[1] 169
1.2.3 Exercise 5
What is the result of summing all numbers from 1 to 100?
# sequence of numbers from 1 to 100 in steps of 1
numbers_1_to_100 <- seq(from = 1, to = 100, by = 1)
# sum over the vector
result <- sum(numbers_1_to_100)
# print the result
result
[1] 5050
# alternative solution
result <- sum(1:100)
The result is 5050.
1.2.4 Exercise 6
Using the London borough data, create a CSV file that contains the following columns:
The names of the London Boroughs
Population change between 1811 and 1911
Population change between 1911 and 1961
Population change 1961 and 2011
# First we load the dataset (if you haven't done it already)
pop <- read.csv("https://data.london.gov.uk/download/historic-census-population/2c7867e5-3682-4fdd-8b9d-c63e289b92a6/census-historic-population-borough.csv")
# Now we select the variables to use for the new dataset. Note that I am using a mathematical function (substracting) within the data.frame() function. This way, I can get the population changes.
pop_new <- data.frame(pop$Area.Name, pop$Persons.1911-pop$Persons.1811, pop$Persons.1961-pop$Persons.1911, pop$Persons.2001-pop$Persons.1961)
# Now we change the names of the columns with the colnames() functions
colnames(pop_new) <- c("London_Borough", "Change_1911_1811", "Change_1961_1911", "Change_2001_1961")
1.2.5 Exercise 7
Which Boroughs had the fastest growth during the 19th Century, and which had the slowest?
# We can use the arrange() function to sort the
library(tidyverse)
pop_sorted <- arrange(pop_new,
desc(Change_1911_1811)) # use desc() to make it descending order
# most growth
head(pop_sorted)
London_Borough Change_1911_1811 Change_1961_1911 Change_2001_1961
1 Greater London 5859000 835094 -825037
2 Inner London 3893000 -1509119 -726816
3 Outer London 1967000 2344213 -98221
4 Southwark 440000 -265587 -68546
5 Newham 417000 -161612 -21504
6 Tower Hamlets 390000 -364318 -9599
# least growth
tail(pop_sorted)
London_Borough Change_1911_1811 Change_1961_1911 Change_2001_1961
31 Sutton 49000 115095 10672
32 Harrow 37000 167080 -2258
33 Barking and Dagenham 35000 138092 -13148
34 Hillingdon 27000 190370 14636
35 Havering 26000 212598 -21336
36 City of London -101000 -15233 2414
The smallest growth (it is actually negative) is from the City of London, while the largest growth was in Southwark. Note, of course, that ‘Greater’, ‘Inner’ and ‘Outer’ are not boroughs.