使用 .SD(I)
.SD 搭配 .SDcols 是非常強大的功能,能大幅簡化對多個欄位的運算。
.SD是一個特殊符號,代表 Subset of Data(資料的子集)。.SDcols指定應納入.SD的欄位。
本練習屬於課程
R 的 data.table 資料操作
練習說明
- 對每個月份,使用
duration搭配which.min(),找出對應最短行程的資料列。 - 結果應包含
month、start_station、end_station、start_date、end_date和duration這些欄位。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
relevant_cols <- c("start_station", "end_station",
"start_date", "end_date", "duration")
# Find the row corresponding to the shortest trip per month
shortest <- batrips[, ___,
by = month(start_date),
.SDcols = ___]
shortest