Chapter 4 Scripting and Writing Functions in R

4.1 Overview

4.3 Building blocks for Programs

4.3.5 Debugging

4.4 Writing Functions

4.6 Apply functions

4.7 Manipulating data with dplyr

# A tibble: 103 x 4
   dest  count OrLat OrLon
   <chr> <int> <dbl> <dbl>
 1 ABQ     254  40.7 -74.2
 2 ACK     265  40.7 -74.2
 3 ALB     439  40.7 -74.2
 4 ATL   17215  40.7 -74.2
 5 AUS    2439  40.7 -74.2
 6 AVL     275  40.7 -74.2
 7 BDL     443  40.7 -74.2
 8 BGR     375  40.7 -74.2
 9 BHM     297  40.7 -74.2
10 BNA    6333  40.7 -74.2
# ... with 93 more rows

4.8 Answers to self-test questions

Q1

Q2

Q3 part i)

Q3 part ii)

Q4

Q5

Q6

Q7

Q8

# Part 1: the join 
flights2 <- flights2 %>% left_join(airports, c("dest" = "faa"))
flights2 <- flights2 %>% select(count,dest,OrLat,OrLon,
                                DestLat=lat,DestLon=lon)
# get rid of any NAs
flights2 <- flights2[!is.na(flights2$DestLat),]
flights2
# Part 2: the plot
# Using standard plots
dest.eg <- matrix(c(flights2$DestLon, flights2$DestLat), ncol = 2)
origin.eg <- matrix(c(flights2$OrLon, flights2$OrLat), ncol = 2)
map("usa", fill=TRUE, col="white", bg="lightblue")
points(dest.eg, col="red", pch=16, cex = 1)
points(origin.eg, col = "cyan", pch = 16, cex = 1)
for (i in 1:nrow(dest.eg)) {
    lines(gcIntermediate(dest.eg[i,], origin.eg[i,], n=50, 
                         breakAtDateLine=FALSE, 
                         addStartEnd=FALSE, sp=FALSE, sepNA))
}
# using ggplot
all_states <- map_data("state") 
dest.eg <- data.frame(DestLon = flights2$DestLon, 
                      DestLat = flights2$DestLat)
origin.eg <- data.frame(OrLon = flights2$OrLon, 
                        OrLat = flights2$OrLat)
library(GISTools)
# Figure 2 using ggplot
# create the main plot
mp <- ggplot() +
    geom_polygon( data=all_states, 
            aes(x=long, y=lat, group = group),
            colour="white", fill="grey20") +
  coord_fixed() +
    geom_point(aes(x = dest.eg$DestLon, y = dest.eg$DestLat),
               color="#FB6A4A", size=2) +
    theme(axis.title.x=element_blank(),
        axis.text.x=element_blank(),
        axis.ticks.x=element_blank(),
        axis.title.y=element_blank(),
        axis.text.y=element_blank(),
        axis.ticks.y=element_blank())
# create some transparent shading
cols = add.alpha(colorRampPalette(brewer.pal(9,"Reds"))(nrow(flights2)), 0.7)
# loop through the destinations
for (i in 1:nrow(flights2)) {
  # line thickness related flights
  lwd.i = 1+ (flights2$count[i]/max(flights2$count))
  # a sequence of colours
  cols.i = cols[i]
  # create a dataset
  link <- as.data.frame(gcIntermediate(dest.eg[i,], origin.eg[i,], n=50, 
            breakAtDateLine=FALSE, addStartEnd=FALSE, sp=FALSE, sepNA))
  names(link) <- c("lon", "lat")
  mp <- mp + geom_line(data=link, aes(x=lon, y=lat), 
                       color= cols.i, size = lwd.i)
}
# plot! 
mp