---
title: "Practice / Getting to know R"
author: "Martin Schedlbauer"
date: "Summer 2023"
output:
  html_document:
    df_print: paged
---

## Question 1 / Load a CSV

The first step is to load the data from the CSV file into a dataframe.

```{r Q1LoadCSV}
url <- "https://s3.us-east-2.amazonaws.com/artificium.us/datasets/FlightsWithAirlines.csv"

df.flights <- read.csv(url,
                       header = T,
                       stringsAsFactors = F)
```

```{r echo=F, eval=F}
head(df.flights, 3)
```

```{r}
tail(df.flights, 3)
```

```{r}
str(df.flights)
```

Display only the carrier, flight, origin, and destination columns from the dataframe.

```{r}
head(df.flights[,c("carrier","flight", "origin", "dest")])
```


Calculate the average (mean) departure delay (column named dep_delay) and display the result in R using the cat() function. Hint: Look up functions in Help in R Studio or online.

```{r}
mean.dep_delay <- mean(df.flights[,"dep_delay"])

print(paste0("Average Departure Delay = ", round(mean.dep_delay, 1)))
cat("Average Departure Delay = ", round(mean.dep_delay, 1))
```


Add a new column ‘tod’ to the data frame with a value of “am” or “pm” depending whether the departure time was AM (before 12 noon) or PM (on or after 12 noon). The time in the data file is in 24-hour format. Hint: Look up how to use the ifelse function. Use the dep_hr column. Print the dataframe to ensure the new column is there and is correct, but only display the carrier, flight, dep_ht, and the new tod columns.

```{r}
df.flights$tod <- ifelse(df.flights$dep_hr < 12, "AM", "PM")
head(df.flights[,c("dep_hr","tod")])
```

```{r}
for (i in 1:nrow(df.flights)) {
  if (df.flights[i,"dep_hr"] < 12)
    df.flights$tod[i] <- "AM"
  else
    df.flights[i,"tod"] <- "PM"
}

head(df.flights)
```


For each flight, display the carrier, flight number, and the actual departure time (scheduled departure plus departure delay) for flights that were delayed. Display the time in the format hh:mm in 24-hour format, e.g., display 23:20 rather than 11:20 or 11:20PM.

```{r}
df.delayed <- df.flights[which(df.flights$dep_delay > 0),
                         c("carrier","flight","dep_hr","dep_min","dep_delay")]

df.delayed$actual <- df.delayed$dep_hr * 60 + (df.delayed$dep_min + df.delayed$dep_delay)
df.delayed$actual <- paste0((df.delayed$actual %/% 60), ":", 
                            ifelse(df.delayed$actual %% 60 < 10,
                                   paste0("0",df.delayed$actual %% 60),
                                   df.delayed$actual %% 60))

head(df.delayed)
```

The solution could be made a bit cleaner with additional intermediary values.
