Loading Packages

We need to first load the packages and data needed for our analysis.

pacman::p_load(tidyverse, knitr, nycflights13) #Loads specified packages
data(flights)

For Loops

Let’s export 3 csv files, one for each origin airport’s flights during the month of January. Let’s do this using a for loop.

nyc_airports <- c("EWR", "LGA", "JFK") #Creates a character vector that has each NYC airport

for (i in c(1:3)) #For loop that exports a csv file for each NYC airport's flights in January
{
  flights %>% 
    filter(month == 1 & origin == nyc_airports[[i]]) %>% 
    write_csv(paste0("./", nyc_airports[[i]], ".csv"))
}

Let’s get screenshots of the 3 exported csv files so we can see information for each one.

knitr::include_graphics("EWR_screenshot.png")

knitr::include_graphics("JFK_screenshot.png")

knitr::include_graphics("LGA_screenshot.png")

Creating a Function

Let’s create a function that takes a number as an input and returns “zat” if it is divisible by 3, “bat” if it divisible by 5, and “zatbat” if it is divisible by 5 and 3. If it isn’t divisible by 3 or 5, the number will be returned.s birthday.” Let’s select only for days of the month that are the 22nd, 23rd, and the 24th.

zatbat <- function(x)
{
  if (x %% 3 == 0 && x %% 5 == 0)
  {
    print("zatbat")
  }
  else if (x %% 3 == 0)
  {
    print("zat")
  } 
  else if (x %% 5 == 0)
  {
    print("bat")
  }
  else
  {
    print(x)
  }
}

Let’s test our function.

#Check case of a number divisible by 3
zatbat(9)
## [1] "zat"
#Check case of a number divisible by 5
zatbat(10)
## [1] "bat"
#Check case of a number divisible by 3 and 5
zatbat(45)
## [1] "zatbat"
#Check case of a number not divisible by 3 or 5
zatbat(8)
## [1] 8

Our function zatbat() works correctly.