+ - 0:00:00
Notes for current slide
Notes for next slide

Practice for data.table

with 7 questions

2023-10-27

1

Before starting...

  • You can write your own answer in each question

  • Don't forget to import library data.table

library(data.table)
  • We will use flights data in nycflights13 library and remove NA
library(nycflights13)
data("flights")
flights <- as.data.table(flights) |> na.exclude()
2

Question 1


Get all the flights in the May 15th

ans <- flights[month == 5 & day == 15]
3

Question 2


Sort flights first by column 'month' in ascending order, and then by 'day' in decending order

ans <- flights[order(month, -day)]
4

Question 3


Select both arr_delay and dep_delay columns

ans <- flights[, .(arr_delay, dep_delay)]
head(ans)
## arr_delay dep_delay
## 1: 11 2
## 2: 20 4
## 3: 33 2
## 4: -18 -1
## 5: -25 -6
## 6: 12 -4
5

Question 4


How many trips have had total delay(arr_delay + dep_delay) > 0?

ans <- flights[, sum( (arr_delay + dep_delay) > 0 )]
ans
## [1] 135059
6

Question 5


Calculate the average arrival and departure delay for all flights in the may 15th

ans <- flights[month == 5 & day == 15,
.(m_arr = mean(arr_delay), m_dep = mean(dep_delay))]
ans
## m_arr m_dep
## 1: -2.029598 9.809725
7

Question 6


How can get the number of trips corresponding to each origin airport?

ans <- flights[, .(.N), by = .(origin)]
ans
## origin N
## 1: EWR 117127
## 2: LGA 101140
## 3: JFK 109079
8

Question 7


How can we get the average arrival and departure delay for each origin and month?

ans <- flights[,
.(mean(arr_delay), mean(dep_delay)),
by = .(origin, month)]
9

Thank you


10

Before starting...

  • You can write your own answer in each question

  • Don't forget to import library data.table

library(data.table)
  • We will use flights data in nycflights13 library and remove NA
library(nycflights13)
data("flights")
flights <- as.data.table(flights) |> na.exclude()
2
Paused

Help

Keyboard shortcuts

, , Pg Up, k Go to previous slide
, , Pg Dn, Space, j Go to next slide
Home Go to first slide
End Go to last slide
Number + Return Go to specific slide
b / m / f Toggle blackout / mirrored / fullscreen mode
c Clone slideshow
p Toggle presenter mode
t Restart the presentation timer
?, h Toggle this help
oTile View: Overview of Slides
Esc Back to slideshow