exercise 5.7.1
1. prob 2
Which plane(tailnum) has the worst on-time record?
tailnum_gr <- flights %>% group_by(tailnum) %>%
summarise(arr_delay_mean = mean(arr_delay, na.rm =TRUE), count = n()) %>% arrange(desc(arr_delay_mean))
tailnum_gr
tailnum 'N844MH'가 가장 안 좋은 기록을 가지고 있다는 것을 확인할 수 있다.
다른 접근 방법도 있다.
flights %>% arrange(desc(arr_delay)) %>%
select(tailnum, arr_delay)
2. prob 3
What time of day should you fly if you want to avoid delays as much as possible?
일단, 그 전에 최대한 지연을 피하려면 며칠 날 비행기를 타야하냐?! (개인적으로 궁금했다.)
flights %>% group_by(month, day) %>%
summarise(mean = mean(dep_delay, na.rm =TRUE), n = n()) %>%
arrange(mean)
9월 24일 비행에서는 웬만하면 꿀을 빨 수 있다.
그럼 문제에서의 질문인 하루 중 몇시에 타야하는가에 대한 답을 찾아보도록 하자.
delay_sum <- flights %>% group_by(hour) %>%
summarise(mean_arr_delay = mean(arr_delay, na.rm = TRUE),
mean_dep_delay = mean(dep_delay, na.rm = TRUE),
weight = (mean_arr_delay + mean_dep_delay)/2,
count = n()) %>%
arrange(weight)
기록으로만 보면 5시가 맞지만 count가 적기 때문에 2순위인 7시에 비행기를 타는게 정신 건강에 좋을 것이다.
3. prob 4
For each destination, compute the total minutes of delay, For each flight, compute the proportion of the total delay for its destination.
목적지별로 arr_delay의 합을 계산하고, 항공편별로 목적지별 arr_delay의 비율을 계산해야한다.
flights %>% group_by(dest) %>%
summarise(arr_delay_sum = sum(arr_delay[arr_delay > 0], na.rm = TRUE),
arr_delay_mean = mean(arr_delay[arr_delay > 0], na.rm = TRUE)) %>%
arrange(desc(arr_delay_sum))
여기서 뽀인트는 arr_delay가 음수인 값을 계산에 포함시키면 지각한 minutes을 구하는데 문제가 생기기 때문에 positive integer만 집계에 포함하는 것이다.
flightnum = 1
flights %>% group_by(dest) %>%
summarise(arr_delay_sum= sum(arr_delay[arr_delay>0],na.rm = T),
arr_delay_sum_flight = sum(arr_delay[arr_delay>0]*(flight==flightnum),na.rm = T),
num = sum(flight==flightnum) ) %>%
mutate(prop= arr_delay_sum_flight/arr_delay_sum) %>%
arrange(desc(num))
위 코드는 전체 항공편의 arr_delay에 대한 flight number 1인 항공기의 arr_delay 비율과 dest별 운행 횟수, dest별 delay시간을 보여준다.
4. prob 5
Delays are typically temporally correlated: even once the problem that caused the initial delay has been resolved, later flights are delayed to allow earlier flights to leave. Using lag(), explore how the delay of a flight is related to the delay of the immediately preceding flight.
lag()함수를 사용해서 이전의 비행이 이후 비행에 어떤 영향을 미치는지 알아보는 문제이다.
zz <- flights %>% group_by(year, month, day) %>%
mutate(arr_delay_lag = lag(arr_delay))
cor.test(zz$arr_delay_lag, zz$arr_delay, use = 'complete.obs')
zz2 <- flights %>% group_by(year, month, day) %>%
mutate(dep_delay_lag = lag(dep_delay))
cor.test(zz2$dep_delay_lag, zz2$dep_delay, use = 'complete.obs')
도착시간이든 출발시간이든 전 타임의 지연과는 상관관계가 적은 것을 확인할 수 있다.
5. prob 6
Look at each destination. Can you find flights that are suspiciously fast?
목적지별로 유독 이상히 빠른 비행편이 없는지 확인하고 목적지별로 가장 짧았던 비행에 대해서 air_time을 계산하고 어떤 비행편이 가장 in the air에서 지연됐는지 확인해보자.
flights %>% mutate(speed = distance / air_time) %>% arrange(desc(speed)) %>%
select(speed, everything())
우선 거리/시간 으로 분속을 구해서 mutate()를 활용하여 speed변수를 새로이 만들었고 내림차순 정렬 뒤에 select()으로 speed변수를 맨앞으로 나열한 dataframe을 반환했다.
하지만 문제에서는 이상하게 빠른 비행이 있는지 확인하라고 했었고, 내가 받은 결과에서는 특이하게 이상하게 빠른 비행이라고 생각되는 비행은 존재하지 않는 것처럼 보였다. 때문에 시각화를 통해 육감에 자극을 더 줄만한 무언가가 있는지 확인해보기로 했다. ggplot을 사용해보겠다.
flights %>% mutate(speed = distance / air_time) %>% arrange(desc(speed)) %>%
ggplot(aes(dest, speed)) +
geom_boxplot() +guides( x= guide_axis(angle = 90))
box_plot을 통해 dest별 speed의 분포를 확인할 수 있었다. 우리가 첫 코드에서 결과로 보았다. 상위 10위권 내에 있었던 speed들은 모두 이상점에 해당하는 데이터였다. 만약 boxplot을 보지않고 dataframe만으로로 데이터를 판단했다면 모든 비행기 속력에 대해서 잘못된 판단을 할 수 있었다. 이렇게 데이터는 다양한 관점에서 다양한 방법으로 파악하는게 중요하다는 것을 인지시켜주는 예제인 것 같다.
6. prob 7
Find all destinations that are flown by at least two carriers use that information to rank the carriers.
적어도 2개이상의 항공사에 의해서 취급되는 dest를 찾아라~ 단 항공사 순위에 대한 정보를 사용하라는 문젠데.!
항공사 순위를 명시하는 column이 있었나? 확인해본 결과 그런건 없었고. 아마도 n()값이나 n_distinct()인자를 사용하라는 말인거 같았다.
over2_carrier_dest <- flights %>% group_by(dest) %>%
summarise(n = n_distinct(carrier)) %>%
arrange(desc(n)) %>%
filter(n >= 2)
요러면 취급하는 항공사가 2개이상인 dest data를 뽑을 수 있다.
7. prob 8
For each plane, count the number of flights before the first delay of greater than 1 hour.
plane별로 1시간(60분)이상인 첫번째 지연전의 비행횟수를 세어라!. 짱구를 굴려보자.
flights %>% group_by(tailnum) %>%
summarise(cumsum_delay = cumsum(arr_delay >= 60)) %>%
filter(cumsum_delay ==0) %>%
summarise(n = n())
우선 항공기의 tailnumber vector인 tailnum별로 flights data를 그루핑하고 summarise()로 arr_delay가 60이상인 행의 arr_delay에 대해서 누적합을 구한다. 그리고 누적합이 0인 값들에 대해서 filter를 뜬다. 그럼 데이터에는 arr_delay가 60보다 작은 행들에 대한 데이터만 존재할 것이다. 그리고 n()을 사용하여 개수를 count한다.
이것은 group_by와 summarise()가 데이터 내부를 변형시키지 않는다는 개념을 인지했을 때 응용이 가능한 부분인거 같다. 나도 지금은 대충 이해된 느낌정도만 든다.
어렵다리.~~
'R > Exploratory data analysis' 카테고리의 다른 글
R for Data Science:: tidy data (1) | 2023.06.09 |
---|---|
R for Data Science::tibbles and data import (0) | 2023.06.08 |
R for Data Science::transformation2 ; grouped (0) | 2023.06.07 |
R for Data Science::transformation (0) | 2023.06.06 |
R for Data Science::scales 2 (0) | 2023.05.24 |